JPA and Entity manager.

Hi all,
I have a "simple" question:
Should I create a class to manage entity manager and entity manager factory on JPA2?
Why do I ask that? Because I read on J2EE tutorial:
With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
To obtain an EntityManager instance, inject the entity manager into the application component:
@PersistenceContext
EntityManager em;
I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.
The wizard that creates the JSF's pages from entity class does a good work but I have some problem in the other classes.
When I call EntityManager it returns null!
The strange thing is that it works properly the first time, when I recall the EntityManager from another xhtml page and from another class the entity manager returns NULL!
So I would understand if the creation of a class for manage the EntityManagerFactory and EntityManager could help me.
Thank you for your future help!

Filippo Tenaglia wrote:
Hi all,
I have a "simple" question:
Should I create a class to manage entity manager and entity manager factory on JPA2?That question is far from complete, as the answer to this one is "depends on what you want to do!"
Why do I ask that? Because I read on J2EE tutorial:
With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
To obtain an EntityManager instance, inject the entity manager into the application component:
@PersistenceContext
EntityManager em;
Given this information...
I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.That answer to your question is "NO", because you have a container available to you that can do the work (Glassfish). It makes no sense using Glassfish and then purposely ignoring the features it has to offer.
Lets get back to basics: you are doing something wrong here. You have to figure out what, you can only do that if you keep studying and getting a more complete understanding. If you are having trouble realizing that, perhaps you should start over without the help of any wizard at all; wizards are only useful when you are already experienced, right now the fact that code is generated is hindering you a lot because you will have a strong impulse to believe there can be no mistake; unfortunately there is no such safety net. The fact that you used the word "weird" is enough proof of this by the way. There is nothing weird here, just a mistake being made that has to be corrected.
And for the future: what IDE (Netbeans in your case) you use to develop really makes absolutely no difference at all. What is more interesting is which version of Java your are using, which can likely be Java 6 or Java 7 nowadays.

Similar Messages

  • JPA and Session Managment

    Hi ,
    am using JPA/Toplink , with Bean Managed entity manager (EntityManagerFactory) , as far as i know that for each EntityManager there should be one active transaction within one session , is that right !!? and how does EntityManager handles these connections (Creation , Closing , ... ) on both ways (direct DB url and non JTA DataSource) , and does the transaction type of the Statless session bean that hosts the execution matters !!!
    Thanks

    Yes, entity managers are allowed to have one transaction active at any given time.
    Assuming that you have a resource-local entity manager (from your comment about JDBC and non-JTA data sources) then any container-managed transaction associated with a session bean is going to be a JTA transaction and be completely independent of the entity manager transaction (as long as the non-JTA-data source is properly set to a data source that is not a JTA data source).
    If you are using a non-JTA data source element to configure your database then the entity manager will simply do a getConnection() on the data source. If you are using the JDBC persistence properties in persistence.xml then the connection will be obtained directly from the JDBC driver.

  • Multitenancy and Entity Manager

    We are using JPA with eclipse link. We have extensive JPA queries. Our code is in production for a while. Now we have  a business use case, to support multitenancy.
    We will be using the Oracle Pluggable Database mechanism where each client will have their database.
    In our code, in order to create an EntityManager, we have defined a Singleton Class.
    In places where we do any JPA queries, we fetch the EntityManager object from this Singleton Class and store the instance of EntityManager as a static variable and reuse in our code.
    In multitenant use case, will the EntityManager instance be specific to the database of each of the client?
    My doubt is do we need to change our model of preparing the EntityManager and  instantiate the EntityManager at class level or the current model works without any issues?

    An EntityManager is meant to be a short lived object, either per request, per transaction, or per user session at most.  You should not be storing an EntityManager in a static variable and sharing among multiple users or threads.
    You should have a single EntityManagerFactory, but create an EntityManager per request.
    For multitenancy, if you have multiple databases, then you will want to create a new EntityManagerFactory per tenant, using the Persistence.createEntityManagerFactory() API, and pass a Map of properties including the tenant's database url.

  • JPA OC4J Entity Manager query.getResultList

    Hello All,
    I am using JPA with OC4J version 10.1.3.3. I am trying to query the database useing enitityManager.createQuery() and requirementList = requirementQuery.getResultList();. It is freezs on executing this statement and i can not see any errors in the log files. I verified the following log files in OC4J
    1)$ORACLE_HOME/j2ee/RMS/application-deployments/RMS/RMS_default_group_1/application.log
    2)$ORACLE_HOME/j2ee/RMS/log/RMS_default_group_1/oc4j/log.xml
    3)$ORACLE_HOME/opmn/logs/default_group~RMS~default_group~1.log
    Please find the peice of code i am using below. It prints the debug statement log.debug("test 411"); in the log file.
    Please some body help me to resolve this issue.
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    private List<Requirement> getLatestRequirementsForRequest(Request request) throws RMSApplicationException,
    RMSSystemException,
    Exception {
    log.debug("\n\n\n###############################\n\ninside getLatestRequirementsForRequest 1");
    String latestRqmtQry =
    //" and rqmt.reqmt_timestamp = :requestReceived " +
    // " and rqmt.reqmtClientReference is null" +
    // " and req.requestContract in ( " + contractNumbers + " )" +
    // " or req.request_proposal in ( " + contractNumbers + " )" +
    " select rqmt from Requirement rqmt, Request request " +
    " where request.parent.requestId = :requestId" +
    " and rqmt.reqmt_timestamp = request.requestReceived " +
    " and rqmt.requirementStatus.reqmtStatusName ='Outstanding' " +
    " and rqmt.reqmtType = 1 " +
    " and request.requestStatus.requestStatusName not in ( 'Completed' ,'Cancelled' )";
    log.debug("sal: qry for rqmtlist " + latestRqmtQry);
    List<Requirement> requirementList = new ArrayList<Requirement>();
    try {
    log.debug("sTest41");
    Query requirementQuery = entityManager.createQuery(latestRqmtQry);
    log.debug("requesId="+request.getRequestId());
    requirementQuery.setParameter("requestId", request.getRequestId());
    log.debug("test 411");
    // requirementQuery.setFlushMode()
    requirementList = requirementQuery.getResultList();
    // requirementList =(List)em.createNamedQuery("Requirement.findLatestRqmtsForContracts").setParameter("contractNumbers",contractNumbers);
    log.debug("requirementList.size = " + requirementList.size());
    log.debug("requirementList = " + requirementList);
    } catch (RuntimeException e) {
    //ctx.setRollbackOnly();
    log.error("Runtime Exception while getting the requirements:",e);
    throw e;
    } catch(Exception e){
    log.error("Exception while getting the requirements:",e);
    throw e;
    log.debug("Test71");
    return requirementList;
    }

    SQL Query is select query using 4 tables. I verified with the data base when i get encounter this problem there are no locks on any of the tables. I also see that the session to the data base completes smoothly. So it proves there is no problem with data base.
    Please note that this kind of behaviour i am seeing with only perticular cases around 2 to 5% of cases. This code i am using from last 6 months.
    Could you please let me know how to get stack dump?

  • JPA and logging entity changes

    Good day!
    I need to log all entity property changes in scope of current transaction in j2ee application. I use Glassfish and JPA. Is there any way to do this?

    Filippo Tenaglia wrote:
    Hi all,
    I have a "simple" question:
    Should I create a class to manage entity manager and entity manager factory on JPA2?That question is far from complete, as the answer to this one is "depends on what you want to do!"
    Why do I ask that? Because I read on J2EE tutorial:
    With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction.
    To obtain an EntityManager instance, inject the entity manager into the application component:
    @PersistenceContext
    EntityManager em;
    Given this information...
    I'm using JSF2, JPA2, JTA and Glassfish3.1 on the NetBeans 7.0.1.That answer to your question is "NO", because you have a container available to you that can do the work (Glassfish). It makes no sense using Glassfish and then purposely ignoring the features it has to offer.
    Lets get back to basics: you are doing something wrong here. You have to figure out what, you can only do that if you keep studying and getting a more complete understanding. If you are having trouble realizing that, perhaps you should start over without the help of any wizard at all; wizards are only useful when you are already experienced, right now the fact that code is generated is hindering you a lot because you will have a strong impulse to believe there can be no mistake; unfortunately there is no such safety net. The fact that you used the word "weird" is enough proof of this by the way. There is nothing weird here, just a mistake being made that has to be corrected.
    And for the future: what IDE (Netbeans in your case) you use to develop really makes absolutely no difference at all. What is more interesting is which version of Java your are using, which can likely be Java 6 or Java 7 nowadays.

  • How to use application managed entity manager in EJB?

    I finish reading The EntityManager Interface in JEE tutorial.
    I know I can use container manager entity manager in EJB, but I want to explore how to use application managed entity manager in EJB.
    Can I use application managed entity manager in EJB (container management JTA transaction is used)? Where do I should close entity manager if can?
    The following is an example from JEE tutorial, but didn't find where to calose entity manager. and can I create mutiple EntityManagerFactory objects and Entity Manager objects to use them in a JTA transaction?
    @PersistenceUnit
    EntityManagerFactory emf;
    EntityManager em;
    @Resource
    UserTransaction utx;
    em = emf.createEntityManager();
    try {
      utx.begin();
      em.persist(SomeEntity);
      em.merge(AnotherEntity);
      em.remove(ThirdEntity);
      utx.commit();
    } catch (Exception e) {
      utx.rollback();

    Seems like a very poor example, the whole power of EJBs is to use Container Managed Transactions so you don't NEED to manage the transaction and the entity manager yourself. What you posted is code I would expect in a non-JEE application, or in a piece of code which requires fine-tuned transaction boundaries such as batched data importing logic.
    If I were you I'd research JPA in steps.
    a) learn about JPA as an API outside of the scope of EJBs (recommended reading: the book 'Pro JPA 2')
    b) learn about Container Managed Transactions in EJBs
    c) learn about Bean Managed Transactions in EJBs
    Right now you're rushing into c). I can understand that it raises many question marks at this point.

  • JPA and Generics

    Hi,
    please consider the following code snippet:
    @Entity
    @Table(name = "MS")
    @DiscriminatorColumn (name="TYPE",discriminatorType=DiscriminatorType.INTEGER)
    public abstract class MS<T extends M> implements java.io.Serializable {
        @JoinColumn(name = "M_ID", referencedColumnName = "ID")
        @ManyToOne(fetch=FetchType.LAZY)
        private T m;
    @Entity
    @DiscriminatorValue("0")
    public class BS extends MS<B> implements java.io.Serializable {
    @Entity
    @Table (name="M")
    @DiscriminatorColumn (name="TYPE",discriminatorType=DiscriminatorType.INTEGER)
    public abstract class M<T extends MS> implements java.io.Serializable {
        @OneToMany(mappedBy="m")
        private Set<T> ms = new HashSet<T>();
    @Entity
    @DiscriminatorValue("0")
    public class B extends M<BS> implements java.io.Serializable {
    }This compiles and deploys fine. However, at runtime JPA is not able
    to figure out what m in the mappedBy attribute refers to.
    It complains that it has a set of type BS which does not have the field m defined. This is true for BS
    but its super class MS has this field defined.
    So I wondering if this is a limitation of JPA or may be I configured something
    wrong!? Is a scenario like above possible with the current JPA?
    Thanks for any help.
    regards.

    No idea!? Let me give an example using Hibernate (you could replace it with JPA though):
    B b = session.get(B.class, Long.valueOf(1));
    Hibernate.initialize(b);In the initialize() process you get an exception, complaining that the Set cannot be resolved because the property m does not exist in class B (which is the type at runtime).
    So I am wondering if it is currently possible to use generics in this way with JPA/Hibernate Entity Manager?

  • How to inherit one enity method and to create entity manager factory

    Hi All,
    i have totally 5 databases where one database has the connection details of all other 4 databases.i am using EJB 3.0 and using MVC architecture.is there any possibility to get the details in that datbase and create entity manager factory based on that detail.i defined all the database connection in persistence.xml.

    Hi,
    is there any oher possibility to create entity manager factory dynamically?

  • JPA and SQL Server 2005's  Identity Don't Play Nice

    I am hoping someone with a little more senior knowledge of JPASQL Server 2005 can point me in the right direction involving SQL Server 2005.
    What I am discovering is JPA and SQL Server 2005 do not playing nice together when you use the IDENTITY capability for
    a primary key. Let me explain. "...when using the IDENTITY as the generator type, the value for the identity field MAY NOT be
    available BEFORE the entity data is saved in the database because typically it is generated when a record is committed."
    My problem is this.
    I have two separate entities using another entity, for example a car has a wheel and a truck has a wheel. I can go through the steps
    of persisting the car and the wheel with no problem. My problem begins when I try to
    find the wheel (by wheel description) for the truck. The query finds the wheel, but does not return the primary key for wheel.
    Therefore, using the PK inside a query generates this error:
    java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation. What has been my appraoch to get the entity to commit to the database is to use the following sequence for the Entity Manager.
    entityManager.persist(wheel);
    entityManager.flush(); I have assumed to this point this action would persist my data because I have been able to retrieve the PK immidately after these steps.
    However, multiple actions taking place within the same transaction, appears to render the persist and flush steps useless. My initial thought
    is to wrap the wheel creation within a new transaction so when the method/transaction completes, the data would be in the database. This
    has not worked.
    I hope I have explained this clear for others to follow. I apologize in advance if I have not. Any suggestions are greatly appreciated.

    I am hoping someone with a little more senior knowledge of JPASQL Server 2005 can point me in the right direction involving SQL Server 2005.
    What I am discovering is JPA and SQL Server 2005 do not playing nice together when you use the IDENTITY capability for
    a primary key. Let me explain. "...when using the IDENTITY as the generator type, the value for the identity field MAY NOT be
    available BEFORE the entity data is saved in the database because typically it is generated when a record is committed."
    My problem is this.
    I have two separate entities using another entity, for example a car has a wheel and a truck has a wheel. I can go through the steps
    of persisting the car and the wheel with no problem. My problem begins when I try to
    find the wheel (by wheel description) for the truck. The query finds the wheel, but does not return the primary key for wheel.
    Therefore, using the PK inside a query generates this error:
    java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation. What has been my appraoch to get the entity to commit to the database is to use the following sequence for the Entity Manager.
    entityManager.persist(wheel);
    entityManager.flush(); I have assumed to this point this action would persist my data because I have been able to retrieve the PK immidately after these steps.
    However, multiple actions taking place within the same transaction, appears to render the persist and flush steps useless. My initial thought
    is to wrap the wheel creation within a new transaction so when the method/transaction completes, the data would be in the database. This
    has not worked.
    I hope I have explained this clear for others to follow. I apologize in advance if I have not. Any suggestions are greatly appreciated.

  • [NewBie] Not able to connect JPA and Hibernate ?

    Hi,
    In last few days I have read some tutorial and started doing JPA and Hibernate tutorials. But I am not able to make it work. Can some one please point out what is that I am doing wrong? Here are the details of what I am doing
    I am using
    IDE : Eclipse EE Indigo
    Following jars
    antlr-2.7.6.jar
    commons-collections-3.2.jar
    dom4j-1.6.1.jar
    hibernate-annotations-3.4.0.GA.jar
    hibernate-commons-annotations-3.1.0.GA.jar
    hibernate-entitymanager-3.4.0.GA.jar
    hibernate-jpa-2.0-api.jar
    hibernate3-3.3.2.GA.jar
    javaee-api-5.0-3.jar
    javassist-3.9.0.GA.jar
    junit-4.8.2.jar
    log4j-1.2.12.jar
    slf4j-api-1.6.1.jar
    slf4j-simple-1.6.1.jar
    sqljdbc.jar => For connecting to MS SQL Server database
    junit-4.8.2 => For testing the application
    The target runtime is set as JBoss 5.0 with jars of JBoss 6.0
    Here is my persistence.xml. This file is under "src\META-INF"
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
         <persistence-unit name="JH1" transaction-type="RESOURCE_LOCAL">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <class>entity.Users</class>
              <exclude-unlisted-classes>false</exclude-unlisted-classes>
              <properties>
                   <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
                   <property name="hibernate.show_sql" value="true"/>
                   <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=TempEPMUser"/>
                   <property name="javax.persistence.jdbc.user" value="user"/>
                   <property name="javax.persistence.jdbc.password" value="password"/>
                   <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
                   <property name="javax.persistence.transactionType" value="RESOURCE_LOCAL"/>
              </properties>
         </persistence-unit>
    </persistence>
    Here is the Users.java code. This is the entity class created using the context menu item JPA Entities from tables
    package entity;
    import java.io.Serializable;
    import javax.persistence.*;
    import java.sql.Timestamp;
    import java.math.BigDecimal;
    * The persistent class for the Users database table.
    @Entity
    public class Users implements Serializable { 
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="Usr_UserID")
    private long usr_UserID;
    @Column(name="Usr_DeptId")
    private BigDecimal usr_DeptId;
    public Users() { 
    public long getUsr_UserID() { 
    return this.usr_UserID;
    public void setUsr_UserID(long usr_UserID) { 
    this.usr_UserID = usr_UserID;
    Here is the testing code TestUser.java
    package testentity;
    import java.util.List;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
    import javax.persistence.PersistenceException;
    import org.apache.log4j.BasicConfigurator;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import entity.Users;
    public class TestUser {
         private EntityManagerFactory emf;
         private EntityManager em;
         @Before
         public void initEmfAndEm(){
              BasicConfigurator.configure();
              try {
                   emf = Persistence.createEntityManagerFactory("JH1");
              } catch (PersistenceException pe) {
                   System.out.println(pe.getMessage());
              em = emf.createEntityManager();
         @After
         public void cleanup() {
              em.close();
         @Test
         public void emptyTest() {
              EntityTransaction et = em.getTransaction();
              et.begin();
              @SuppressWarnings("unchecked")
              final List<Users> listUser = em.createQuery("select usr_DeptID from Users").getResultList();
              et.commit();
              for (Users usr: listUser){
                   int depid = usr.getUsr_DeptId().intValue();
                   System.out.println("User Department id is "+depid);
    When I execute the code I get following error message
    java.lang.UnsupportedOperationException: The user must supply a JDBC connection
    at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1354)
    at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:38)
    at testentity.TestUser.emptyTest(TestUser.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

    Hi,
    Try following the JPA tutorials for WebLogic, JPA using EclipseLink or Hibernate will be the same if you stick to the specification. WebLogic 10.3.4.0 ships with a Java EE 6 compliant JPA 2.0 implementation in EclipseLink - you may want to give that a try.
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/WebLogic_Web_Tutorial
    http://wiki.eclipse.org/EclipseLink/Examples/Distributed
    I also have a JBoss 6 tutorial for getting JPA working as well.
    BTW, your persistence unit is currently application managed - try switching to container managed - then most of your jar dependencies will go away as everything is already setup for you to do dependency injection via the container.
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/JBoss_Web_Tutorial
    thank you
    Michael O'Brien
    http://www.eclipselink.org

  • TL 11g: JPA and DB proxy authentication?

    Hi!
    I posted similar question of JDev 11g forum, but I hope I can get more profound expertise here :)))
    OK. I want to make a proof-of-concept for end-to-end security using a novel 11g technology: I want to use EJB 3.0 / JPA (TopLink) and to enable subject identity propagation to database using Proxy Authentication mechanism. I stress that I want to use JPA (annotated entities) and not TopLink mappings, and to have as simplest as possible code (yes, I know...).
    Now, my idea is to use Session Event Listener (registered in persistance.xml) to set a proxy connection inside a standard unit of work connection defined in persistance.xml (in the proxy connection I would not set username/password in event listener as I want to do that inside EJB Session Facade).
    Then, in EJB Session Fascade I would like to set a username/password for database login in session that will be used to execute a JPA transaction. I discovered that I can get a ServerSession and Active Session from Entity Manager, with:
    EntityManager em = emf.createEntityManager();
    ServerSession serverSession = ((oracle.toplink.jpa.JpaEntityManager)em).getServerSession();
    Session activeJPASession  = ((oracle.toplink.jpa.JpaEntityManager)em).getActiveSession();What I don't know is how to proceed. Do I have to use Server Session to create/open a new Client Session (but, I'm not sure if then I also have to use a manual transactions inside EBJ Session Bean method, or I can rely on container managed transaction?)? Or I can just set username/password on Active Session. Or I can change a DatabaseLogin (ActiveSession.getLogin().setUsername().setPassword())?
    Please, any advice is appreciated. I'm not an expert on JPA/TopLink so I may spend days figuring this out...
    Thanks in advance!
    PaKo

    PaKo,
    We need to make proxy authentication easier through the JPA interface. At present you can configure the event listener using the toplink.session-event-listener to implement the proxy events as described in the documentation. The piece that is missing is the ability to pass in the proxy authentication credentials when acquiring an EntityManager.
    You are correct that you would need to acquire a client session directly (Note: the JpaHelper can help). When acquired you can use this client session to access the database but it will function only as TopLink's native API and not completely as JPA.
    I filed bug 219434 against EclipseLink to address passing the credentials into:
    EntityManagerFactory.createEntityManager(Map properties)I will continue to investigate to get you a better solution.
    Doug

  • Can I create two entity manager factoris in one app?

    I need to develop two projects, both need JPA access to same data source.
    One is an web project, the other is java se project. And web project needs to the some methods inside java se project.
    I created two separate JPA set(persistence.xml and entity classes). Both project can run separately however, if I call the methods inside java se project from the web project.
    entity manager inside that project won't be created successfully, says error:
    oracle.toplink.essentials.exceptions.DatabaseException Internal Exception: java.sql.SQLException: No suitable driver found
    I am very confident that mysql driver lib has been added for both projects.
    Does anyone know what is wrong here? Thanks!

    Yes. Reduce the number of FDM applications you are creating. You can have multiple target system adapters in a single FDM application (i.e. a single database only required). There is no need to create a new application for each target system.

  • Problem with non-container managed entity manager

    i am working on a project, in which i am using entity beans.i use netbeans, glassfish as application server and toplink as persistence provider .
    i created a java class that handles all the operations with the entitys, which means i using non-container managed entity manager.
    in the constructor
    try{
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("voidPU");
                entityManager = emf.createEntityManager();
            catch(Exception ex){
                throw new EJBException(ex.getMessage());
            }then i call a function in this class from a servlet
    the code of the function
    List users = null;
            try {
                ProgLanguages progLanguage = entityManager.find(ProgLanguages.class, languageId);
                users = (List) progLanguage.getUserIdCollection();
            catch(IllegalStateException illegalStateException){
                throw new EJBException(illegalStateException.getMessage());
            catch(IllegalArgumentException illegalArgumentException) {
                throw new EJBException(illegalArgumentException.getMessage());
            }i got an IllegalArgumentException saying Unknown entity bean class: class vanguard.server.entity.ProgLanguages, please verify that this class has been marked with the @Entity annotation
    what confuses me is that sometimes it works and most of the time it does not work, have i made anything wrong?, or there is a problem with any of the tools netbeans, glassfish, or toplink?

    Is it always the same entity that is reported as 'unknown' ? You mention that it works sometimes but is it the same deployment and the same code that works? The first thing I would verify is that the ear is being created as expected by netbeans. Check the persistence.xml file and verify that all of the classes are listed that will be used as entities.
    --Gordon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Topic: How to obtain entity manager in application server?

    Hey,
    How to obtain Entity manger in application server ?
    The class is a simple class (no Ejb), and i can call to this class from Ejb or from inner schdeuler process (not container management)
    I want that if i call to this calss from Ejb , that the entity manager transaction will join to the global transaction.
    Thank you

    Hi,
    entity managers outside EJBs can be created using a javax.persistence.EntityManagerFactory.
    Regards

  • Does refreshing a report that includes Scope and Entity require elevated rights / permissions?

    This relates to the following thread:
    Why does refreshing a report in the EPM Add-In need to edit the Ownership Manager?
    Since I've received no responses on the above thread, I thought I might approach this from a different angle.
    If we have a report that includes both Scope and Entity, in SAP BPC 10 NW (801 SP03) / EPM Add-In 10.0 SP 16 Patch 1, does this require a user to have elevated permissions in order to refresh the report?  I ask because I have users who have rights to view reports, but they error out when they try to refresh a report's data, only where Scope and Entity are used in the report.  The tasks that error are:
    P0081
    Run Consolidation Tasks
    P0082
    View Ownership Manager
    P0083
    Edit Ownership Manager
    I do not understand why any of these should even be called by refreshing the report, as the user is simply "viewing" data that already exists in the environment.
    Can someone please shed some light on this or point me in the direction of how I can go about resolving this issue?
    Your help is greatly appreciated.
    Jeff

    Hi
    I am facing the same issue despiste the elevated app permission as per
    https://msdn.microsoft.com/en-us/library/office/jj822159.aspx?f=255&MSPPError=-2147217396
    I still had the error 401
    the solution for me was
    Under list settings -> advanced settings update the Create and Edit access settings from "Create and edit all items"
    the add the user the right to add only ( no edit , no delete) .
    Eric Caron

Maybe you are looking for

  • Getting the page size in PDF file

    i want know how do get the page size in PDF file befor placing every page in document for example height=297 mm And width=210mm

  • System generated index property not generated in database

    Hi, I created an offline table by copying it from an (first) online database to my project. The table contains a unique key constraint, which references a system generated index. Now I used this offline table to generate a table in another (second) o

  • Mail to vendors abt vendors payment

    Dear all We have one requirement : Generally first we will create batch(  open item ) using zreport. After that we will cleared this batch using f110. My requirement is: When I created batch using z tocde: those  document for clearing  we need to sen

  • Strange looking Safari and crashes?

    Hey there, I have recently had some real stability issues with Safari. It often hangs (with the Beach Ball of Doom) for around 2 minutes when scrolling, and often crashes. Another problem I have is that when scrolling, very often that not the text an

  • Cannot open form - Reader & Acrobat crash

    Hello, I am facing a strange issue here on our citrix servers (Win 2008 x64, Citrix PS 4.5) We have both Acrobat reader 9.4 and Acrobat Std 9.4 installed on the servers (problem occurs with verson 9.3 also) When we try to open some pdf files  (with e