JPA - EntityManager - createQuery - Inheritance

I'm quite new to JPA and I need support on query syntax.
I have an abstract entity:
@MappedSuperclass
public abstract class HACCP implements Serializable {
}and more than one concrete implementations used to differentiate the DB table where data are stored
@Entity
@Table(schema = "dbo", name = "haccp_01")
public class HACCP01 extends HACCP {
@Entity
@Table(schema = "dbo", name = "haccp_02")
public class HACCP02 extends HACCP {
}I want to use only one service to execute CRUD functionalities.
When I retrieve data using the find method of the EntityManager everithing works fine:
em.find(HACCP.class, id);and at runtime the concrete class identifies the correct DB table.
Now I need to write my own query with a where clause
Query query = getEntityManager().createQuery( "select p FROM HACCP p WHERE [...]");obviously forcing the name of the table is not what I want!
How shold I write the query?
Edited by: mbm63 on Aug 1, 2008 11:52 AM

Solved!
I just get the runtime simple name of the argument class and build the query using it:
public HACCP retrieveCurrent(HACCP haccp) {
   Query query = getEntityManager().createQuery( "select p FROM " + haccp.getClass().getSimpleName() + " p WHERE [...]");
}

Similar Messages

  • JPA EntityManager shared across OSGi modules

    Hi,
    I'd like to create an OSGi module which would act as a 'JPA master' making JPA EntityManager available to other OSGi modules. The persistence.xml would be part of this module but it would do nothing more.
    I'd like to then access EntityManager from other OSGi bundles, both JARs and WARs (JAR Bundles and WAR Bundles).
    I'm running on GlassFish 3.1.2.2 and using EclipseLink as the JPA provider.
    Any idea for best practices?
    Thank you

    Hi, thanks for the link.
    It says 'Refer to the examples to see it being used.' without a link so I read the section above that (8. JPA in OSGi Application)
    It says about some config entries in GlassFish, I enabled it but still no luck.
    Here's my /src/main/resources/META-INF/persistence.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence 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_1_0.xsd" version="1.0">
    <persistence-unit name="cmsdbconnection">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
         <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
    <property name="javax.persistence.jdbc.url" value="jdbc:mysql://172.16.145.139:3306/test_db"/>
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    <property name="javax.persistence.jdbc.user" value="db_user"/>
    <property name="javax.persistence.jdbc.password" value="db_user"/>
    <property name="eclipselink.ddl-generation.table-creation-suffix" value="engine=InnoDB" />
    <property name="eclipselink.ddl-generation" value="create-tables" />
    <property name="eclipselink.target-server" value="=SunAS9" />
    </properties>
    </persistence-unit>
    </persistence>
    Maven pom.xml to generate MANIFEST.MF:
    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>2.4</version>
                        <extensions>true</extensions>
                        <configuration>
                             <archive>
                                  <manifestEntries>
                                       <Bundle-ManifestVersion>2</Bundle-ManifestVersion>
                                       <Bundle-SymbolicName>com.ifp.vault.service.persistence</Bundle-SymbolicName>
                                       <Bundle-Version>${project.version}</Bundle-Version>
                                       <Import-Package>org.osgi.framework,org.osgi.util.tracker,javax.persistence;jpa="2.0";version="1.1.0",org.eclipse.persistence.jpa</Import-Package>
                                       <JPA-PersistenceUnits>cmsdbconnection</JPA-PersistenceUnits>
                                       <Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
                                  </manifestEntries>
                             </archive>
                        </configuration>
                   </plugin>
    Deploying in GlassFish succeeds, but I cannot obtain the EntityManagerFactory from other OSGi bundles.
    Should that be registered as an OSGi service anyway? Because I can't see that when listing all OSGi bundles.

  • Problem accesing JPA EntityManager from JSP scriplet

    Hy,
    I am trying to access an EntityManager from JSP scriptlet for testing purposes and it just doesn't work.
    Here is the JSP scriptlet:
    <%
    EntityManager em = (EntityManager) (new InitialContext()).lookup("java:comp/env/persistence/em");
    Query query = em.createQuery("select u from USER u");
    List<User> users = (List<User>) query.getResultList();
    for (User user : users) { user.toString(); }
    %>
    The application is deployed in JBoss 4.2.2.GA.

    Sorry for my previous post. It was incomplete.
    I am trying to access an EntityManager from JSP scriptlet for testing purposes and it doesn't work.
    Here is the JSP scriptlet:
    <%
    EntityManager em = (EntityManager) (new InitialContext()).lookup("java:comp/env/persistence/em");
    Query query = em.createQuery("select u from USER u");
    List<User> users = (List<User>) query.getResultList();
    for (User user : users) { user.toString(); }
    %>
    persistence.xml file :
    <persistence-unit name="myApp">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <jta-data-source>java:/XAOracleDS</jta-data-source>
    <properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect"/>
    </properties>
    </persistence-unit>
    web.xml file :
    <persistence-context-ref>
              <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
              <persistence-unit-name>myApp</persistence-unit-name>
         </persistence-context-ref>
    The application is deployed in JBoss 4.2.2.GA. When I access the JSP page I get the following exception:
    javax.servlet.ServletException: javax.naming.NameNotFoundException: persistence not bound
    I guess I have to configure the resource in jboss-web.xml too, but I don't know how. I tried with <resource-ref>, but I got the same error.
    Any help at all would be highly appreciated !
    Thanks.
    Andrei

  • JPA, EntityManager and RMI

    Hello,
    in my client server application, I want to get a DAO from the server to add or update a business object.
    My problem is that the DAO must have a property with the EntityManager so he can do his job, this EntityManager
    is not serializable, so RMI throw a NotSerializableException, but when I set the property tansient, the EntityManager
    will be null after serialize the DAO to the client.
    How can I solve that problem?
    Thanks.

    teramor1 wrote:
    Thank you! I undestand, the domain objects are not attached and therefor not JPA managed, when some changes are made to the objects.
    When I take a Service Interface and take the implementation from the Rmi Server, so I can call update(...) the ServiceImplementation must have a property to a DAO and the DAO to an EntityManager, but the EntityManager is not serializable.
    How can I detach the ServicImplementation from the DAO and/or the EntityManager so the Client gets the ServiceImplementation and can call the update(...) method and this method can do his job on the dao and the dao can do his job on the EntityManager?Assuming i understand your usage of the word "Service" (and i'm not sure i do), the client will never get an instance of the Service implementation. the Service implementation never leaves the server. a client gets a handle to the Service interface through some sort of jndi lookup. it then invokes remote methods on this Service which may return entity objects. then only things that travel between the client and server are the entity objects themselves.

  • JPA EntityManager connection

    Hi, I'm trying to get into the Java Persistence Api, so I came up with these questions:
    I'm planning to use it in a existing db desktop application, currently using java.sql.connection object to query the mysql server.
    May I share the connection between the JPA and the current logic or should I open a new one for the JPA ?..
    As this is a desktop app, I would like to dinamically create the JPA connection as I do with the java.sql.connection, I dont want setup again in the persistence.xml file, is this possible without create a Datasource?..
    I do appreciate your help!!..

    Using Jboss 4.0.5 + SQLServer. When calling
    con = (Connection) login.connectToDatasource(null);
    I get
    java.lang.Throwable: STACKTRACE
         at org.jboss.resource.connectionmanager.CachedConnectionManager.registerConnection(CachedConnectionManager.java:290)
         at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateConnection(BaseConnectionManager2.java:417)
         at org.jboss.resource.connectionmanager.BaseConnectionManager2$ConnectionManagerProxy.allocateConnection(BaseConnectionManager2.java:842)
         at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:88)
         at oracle.toplink.essentials.jndi.JNDIConnector.connect(JNDIConnector.java:145)
         at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:185)
    at my calling line

  • [JPA] How to avoid excessive joins in queries on InheritanceType.JOINED

    Hi,
    Let me use an over-simplified example to illustrate my question:
    Let's assume I have two classes: SuperClass and SubClass. As the name suggests, SubClass extends SuperClass.
    I have mapped them in JPA via:
    @Inheritance(strategy=InheritanceType.JOINED)
    @DiscriminatorColumn(name="CTYPE", discriminatorType=DiscriminatorType.INTEGER)
    @PrimaryKeyJoinColumn(name="ID")And now let's suppose I run the following query:
    Query q = entityManager.createQuery("select o.id from SubClass o");In this case, TopLink Essentials generates SQL with a join between the base table and the detail table. Why? All I need is the ID which is available in the detail table too. The base table doesn't need to be included in the query.
    Is there a way to avoid the unnecessary join? I even tried mapping the ID column in both entities but it didn't help.
    Best regards,
    Bisser

    Thank you for you reply, Doug!
    I don't want to instantiate SubClass. I only wish to get the ID. I don't need validations or fields from the superclass.
    Should I resort to using native SQL for that?
    (By the way, the real query that I use in my program instantiates a completely different entity. I use the SubClass in a subquery. And I don't need the SuperClass to get involved. I have a foreign key that guarantees that the SuperClass's row exists in the database.)
    Best regards,
    Bisser

  • JPA Problem using alias for columns in a query

    Hello, I am having some problems with a query that I am trying to use in my JEE project. This query doesnt return an entity but a group of values. I created a class representing the result and a query with the jpa constructor expression but it is not working.
    The problem is that in the query I added some alias to the results, and when I try to run the project it says that it cannot parse the query.
    My Query:
    Query query = em.createQuery("SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo"); When I use that the server returns :
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    GRAVE: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    at java.lang.Thread.run(Thread.java:619)
    Caused by: Exception [EclipseLink-8024] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.JPQLException
    Exception Description: Syntax error parsing the query [SELECT NEW vo.VOOperacionesAgrupadas (o.nemotecnico as nemotecnico, o.esCompra as esCompra, i.equivUltimo as equivUltimo, sum(o.saldo) as saldo, sum(o.utilidad) as utilidad, sum(o.tasaCompraVenta)/count(o.nemotecnico) as promedioTasaCompra, (i.equivUltimo-sum(o.tasaCompraVenta)/count(o.nemotecnico))*100 as puntosBasicos) FROM Operaciones o, Instrumentos i WHERE o.idUsuario = :idUsuario AND o.nemotecnico = i.nemotecnico AND o.estaCerrada = 'false' Group by o.nemotecnico, o.esCompra, i.equivUltimo], line 1, column 53: syntax error at [as].
    Internal Exception: MismatchedTokenException(8!=82)
    at org.eclipse.persistence.exceptions.JPQLException.syntaxErrorAt(JPQLException.java:362)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.handleRecognitionException(JPQLParser.java:304)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.addError(JPQLParser.java:245)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.reportError(JPQLParser.java:362)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedElement(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.mismatch(Unknown Source)
    at org.eclipse.persistence.internal.libraries.antlr.runtime.BaseRecognizer.match(Unknown Source)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.constructorExpression(JPQLParser.java:2635)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectExpression(JPQLParser.java:2045)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectItem(JPQLParser.java:1351)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectClause(JPQLParser.java:1266)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectStatement(JPQLParser.java:352)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.document(JPQLParser.java:276)
    at org.eclipse.persist
    GRAVE: ence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:133)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.buildParseTree(JPQLParser.java:94)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:198)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:173)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:125)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:109)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1326)
    ... 59 more
    Caused by: MismatchedTokenException(8!=82)
    ... 74 more
    What can I do?? I have been stuck in this problem for 2 weeks :s I have tried almost everything..
    Thanks in advance for your help!

    SELECT tmp.contract_no, tmp.Actual, tmp.Actual - tmp.NbHours
    FROM ( SELECT t.contract_no, sum(l.hrs) AS Actual, (c.labour_hours * c.labour_progress_per) / 100 AS NbHours
    FROM TASK_DELEGATION t
    INNER JOIN COST_CODE c
    ON t.cost_code = c.cost_code AND t.contract_no = c.contract_no AND t.is_inactive=0
    INNER JOIN Labour.dbo.LABOURALLOT l
    ON l.contractNo = c.contract_no AND l.costcode = c.cost_code AND l.pm = 'N'
    GROUP BY t.contract_no, c.labour_hours, c.labour_progress_per
    ) tmp

  • EJB3.0:JPA :java.lang.IllegalArgumentException

    Im pretty new to this, so Im trying to post everything you need to understand my problem,try to be more clear, i'm in lack of ideas in this problem, even it sounds like a classic
    /*Bean class*/
    public class BookCatalogBean implements Serializable, BookCatalogInterface {
    @PersistenceContext(unitName="EntityBean")
    // @PersistenceContext
    EntityManager em;
    protected BookBank book;
    protected Collection <BookBank> pmnList;
    public void addBook(String title, String author, double price) {
    // Initialize the form
    if (book == null)
    book = new BookBank(title, author, price);
    em.persist(book);
    public Collection <BookBank>getAllBooks() {
    System.out.println("BookCatalogInterface.java:getAllBooks");
    pmnList=em.createQuery("from BookBank book ").getResultList();
    System.out.println("BookCatalogInterface.java:getAllBooks...111:"+pmnList);
    return pmnList;
    /*and this is another class BookBank.java */
    package entity.library;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import java.util.Collection;
    import javax.persistence.*;
    import java.io.Serializable;
    @Entity
    @Table(name="BookBank")
    public class BookBank implements Serializable {
    long id;
    /*variable declaration*/
    public BookBank() {
    super();
    public BookBank(String title, String author, double price) {
    super();
    this.title = title;
    this.author = author;
    this.price = price;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    // Getter and setter methods for the defined properties..
    and I am getting error :-
    BookCatalogInterface.java:getAllBooks
    javax.ejb.EJBException: EJB Exception: ; nested exception is:
    java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Syntax error parsing the query [from entity.library.ConfPmno conf ], line 1, column 0: unexpected token [from].
    Internal Exception: NoViableAltException(32!=[197:1: document : (root= selectStatement | root= updateStatement | root= deleteStatement );]); nested exception is: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Syntax error parsing the query [from entity.library.ConfPmno conf ], line 1, column 0: unexpected token [from].
    Internal Exception: NoViableAltException(32!=[197:1: document : (root= selectStatement | root= updateStatement | root= deleteStatement );])
    java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Syntax error parsing the query [from BookBank book ], line 1, column 0: unexpected token [from].
    Internal Exception: NoViableAltException(32!=[197:1: document : (root= selectStatement | root= updateStatement | root= deleteStatement );])
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at weblogic.deployment.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:93)
    at weblogic.deployment.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:91)
    at weblogic.deployment.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:80)
    at weblogic.deployment.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:26)
    at $Proxy140.createQuery(Unknown Source)
    at entity.library.ConfPmnoBean.getAllBooks(ConfPmnoBean.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
    at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at com.bea.core.repackaged.springframework.jee.spi.MethodInvocationVisitorImpl.visit(MethodInvocationVisitorImpl.java:37)
    at weblogic.ejb.container.injection.EnvironmentInterceptorCallbackImpl.callback(EnvironmentInterceptorCallbackImpl.java:54)
    at com.bea.core.repackaged.springframework.jee.spi.EnvironmentInterceptor.invoke(EnvironmentInterceptor.java:50)
    at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proc
    persistent.xml :-
    <persistence version="1.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_1_0.xsd">
    <persistence-unit name="EntityBean" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>DB_DS</jta-data-source>
    <non-jta-data-source>DB_DS</non-jta-data-source>
    <properties>
    <property name="eclipselink.target-server" value="WebLogic_10"/>
    <property name="eclipselink.logging.level" value="FINEST"/>
    </properties>
    </persistence-unit>
    </persistence>
    I am not able to resolve the issue,getting error while calling getAllBooks method(createQuery line) of BookCatalogBean.java file.
    Any help is much appreciated,Please suggest solution

    Try using:
    em.createQuery("select book from BookBank book").getResultList();instead of
    em.createQuery("from BookBank book ").getResultList();The "from Entity e" only works for the Hibernate query language not the JPA query language.
    Also in your persistence.xml, define only one data-source: a jta-data-source or a non-jta-data-source.

  • Problem with JPA @Embeddable class field in  @Embedded

    I have a Embeddable class and Embadded in all of my JPA Entities, the version(in DBUniqueId) field is mandatory for some JPA Entities and for others it should not be present.
    My DBUser.java JPA Entity shouldn't have version field(DBUser table doesn't have one) and so I didn't include it in @AttributeOverrides of DBUser.java. when I try to run the JPA query it results in exception
    Query:
    List<DBUser> userList = (List<DBUser>)entityManager.createQuery(SELECT u FROM DBUser u WHERE u.userId.root=?1 AND u.userId.extension=?2).setParameter(1,"root1").setParameter(2,"ext1").getResultList ();
    And The Exception is:
    ---- Begin backtrace for Nested Throwables
    java.sql.SQLException: ORA-00904: "T0"."VERSION": invalid identifier
         at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:74)
         at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)
    How do I inform to JPA Entity to ignore only the version field of the Embeddable in my JPA Entity @Embedded place.
    So the above query can successful. Thank You!
    Please guide me to solve this problem.
    @Embeddable
    @MappedSuperclass
    public class DBUniqueId implements Serializable {
    * serialVersionUID.
    private static final long serialVersionUID = 8903598739796209331L;
    * root.
    private String root;
    * extension.
    private String extension;
    * version.
    private String version;
         //Getters & Setters
    @Entity
    @Table(name = "MyTable", schema = "MySchema")
    public class DBUser implements Serializable {
    * unique user id.
    private DBUniqueId uniqueUserId;
    * Get the unique user id.
    * @return <code>DBUniqueId</code> - unique person id
    @Embedded
    @AttributeOverrides( {
    @AttributeOverride(name = "root", column = @Column(name = "LUSR02_ID_ROOT", nullable = true, length = 50)),
    @AttributeOverride(name = "extension", column = @Column(name = "LUSR02_ID_EXT", nullable = true, length = 50))
    public DBUniqueId getUserId () {
    return uniqueUserId;
    * set user unique id.
    * @param uniqueId - unique id of the person
    public void setUserId (final DBUniqueId uniqueId) {
    this.uniqueUserId = uniqueId;
    }

    Sudeep Naidu wrote:
    Hello gimbal2,
    Thanks for your response...
    In my project I have created a class with name DBVersionUniqueId but my lead said no to it.
    Only DBUniqueId should be used and make it work with or with out version fields.
    I tried experimenting around, but didn't succeed.
    Please Suggest some solution to make it work with DBUniqueId class.
    Thank You.No, let your lead write the code. He/she seems to be the expert. I certainly have no clue how to do it and honestly I also cannot find any reason why it should be possible. Let me put what is required in other words:
    - you have an entity with three properties, all of which are not transient. This means these properties map to three columns in the database according to the JPA specs.
    - you have a table with only two properties
    - you must and you shall use the object with three properties but at the same time one of the fields must all of a sudden be ignored by the persistence provider
    It makes no sense to want to do that.
    Correct answer: create a new object with only the two fields so the database and the object model match exactly
    Wrong answer: try to create workarounds that in six months time nobody is going to understand why the hell it was done that way

  • 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 Persistence loading issue - JBOSS 5

    Hello Every One!!
    I have two projects "ProjectA.war" and "ProjectB.war".
    In both projects, i am using Oracle 11g, JPA2 with EclipseLink 2.4.2.
    and i am using JBOSS 5.1.0 GA application server.
    Both have different persistence.xml files with different persistence-unit names, different data-source files.
    Here i am connecting same Oracle DB user for both projects.
    My Problem is...
    First i had deployed ProjectA.war in server. And it is working fine. and DB operations also working fine.
    Now i am deploying the ProjectB.war in server  besides of ProjectA.war.
    So, when i am trying to perform the db operations on ProjectA.war then jboss is searching the POJO classes in ProjectB.war's persistenece.xml file with the help of ProjectB's persistence-unit name.
    But actually it need to search in ProjectA.
    So, what can i do?
    My ProjectA.war Configurations as like below...
    ============ persistence.xml ==================
    <persistence 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
    persistence_2_0.xsd" version="2.0">
              <persistence-unit name="Entity" transaction-type="RESOURCE_LOCAL">
                        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
                        <non-jta-data-source>java:/projectADS</non-jta-data-source>
                        <class>env.model.authorization.IptUsersRoles</class>
                        <class>env.model.defaults.IptUsergroups</class>
                        <class>env.model.defaults.IptUsertype</class>
                        <class>env.model.authorization.IptUsers</class>
                            <properties>
                                  <property name="javax.persistence.jdbc.driver"
                                            value="oracle.jdbc.driver.OracleDriver" />
                                  <property name="javax.persistence.jdbc.url"
                                            value="jdbc:oracle:thin:@x.x.x.x:1521:TEST" />
                                  <property name="javax.persistence.jdbc.user" value="TEST" />
                                  <property name="javax.persistence.jdbc.password" value="TEST" />
                                  <property name="eclipselink.session.customizer" value="entity.jpa.JPAEclipseLinkSessionCustomizer"/>
                                  <property name="eclipselink.logging.level" value="FINEST"/>
                        </properties>
              </persistence-unit>
    </persistence>
    ================= jboss-classloading.xml ===================
    <?xml version="1.0" encoding="UTF-8"?>
    <classloading xmlns="urn:jboss:classloading:1.0"
                                  name="ProjectA.war"
                                  domain="DefaultDomain"
                                  top-level-classloader="true"
                                  parent-domain="Ignored"
                export-all="NON_EMPTY"
                import-all="true"
                parent-first="false">
    </classloading>
    ==================== jboss-web.xml ======================
    <?xml version="1.0" encoding="UTF-8"?>
    <jboss-web>
              <resource-ref>
                        <description>DB Connection</description>
                        <res-ref-name>ProjectADS</res-ref-name>
                        <res-type>javax.sql.DataSource</res-type>
                        <jndi-name>java:/ProjectADS</jndi-name>
                        <res-auth>Container</res-auth>
        </resource-ref>
    </jboss-web>
    My ProjectB.war Configurations as like below...
    ============ persistence.xml ==================
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence 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
        persistence_2_0.xsd" version="2.0">
              <persistence-unit name="IportIBEntity" transaction-type="RESOURCE_LOCAL">
                        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
                        <non-jta-data-source>java:/ProjectBDS</non-jta-data-source>
                        <class>env.model.IptRequestDataRecord</class>
                        <class>env.model.IptResponseDataRecord</class>
                        <properties>
                                  <property name="eclipselink.jdbc.driver"
                                            value="oracle.jdbc.driver.OracleDriver" />
                                  <property name="eclipselink.jdbc.url"
                                            value="jdbc:oracle:thin:@x.x.x.x:1521:TEST" />
                                  <property name="eclipselink.jdbc.user" value="TEST" />
                                  <property name="eclipselink.jdbc.password" value="TEST" />
                                  <property name="eclipselink.session.customizer"
                                            value="entity.jpa.JPAEclipseLinkSessionCustomizer" />
                                  <property name="eclipselink.logging.level" value="FINEST" />
                        </properties>
              </persistence-unit>
    </persistence>
    ================= jboss-classloading.xml ===================
    <?xml version="1.0" encoding="UTF-8"?>
    <classloading xmlns="urn:jboss:classloading:1.0"
                                  name="ProjectB.war"
                                  domain="DefaultDomain"
                                  top-level-classloader="true"
                                  parent-domain="Ignored"
                export-all="NON_EMPTY"
                import-all="true"
                parent-first="false">
    </classloading>
    ==================== jboss-web.xml ======================
    <?xml version="1.0" encoding="UTF-8"?>
    <jboss-web>
              <resource-ref>
                        <description>DB Connection</description>
                        <res-ref-name>ProjectBDS</res-ref-name>
                        <res-type>javax.sql.DataSource</res-type>
                        <jndi-name>java:/ProjectBDS</jndi-name>
                        <res-auth>Container</res-auth>
        </resource-ref>
    </jboss-web>
    And the console error like below ....
    13:26:34,068 INFO  [IportIBEntity] finding IptUsers instance with property: userCode, value: ADMIN
    13:26:34,709 SEVERE [IportIBEntity] find by property name failed
    java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Problem compiling [select model from IptUsers model where model.userCode= :propertyValue].
    [18, 26] The abstract schema type 'IptUsers' is unknown.
    [39, 53] The state field path 'model.userCode' cannot be resolved to a valid type.
              at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1512)
              at env.acegi.users.IptUsersDAO.findByProperty(IptUsersDAO.java:174)
              at env.acegi.users.IptUsersDAO.findByUserCode(IptUsersDAO.java:185)
              at env.acegi.security.AcegiAuthentication.loadUserByUsername(AcegiAuthentication.java:51)
              at org.acegisecurity.providers.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:99)
              at org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:122)
              at org.acegisecurity.providers.ProviderManager.doAuthentication(ProviderManager.java:200)
              at org.acegisecurity.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:47)
              at org.acegisecurity.ui.webapp.AuthenticationProcessingFilter.attemptAuthentication(AuthenticationProcessingFilter.java:74)
              at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:252)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.concurrent.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:95)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
              at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
              at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
              at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
              at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
              at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
              at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
              at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
              at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
              at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
              at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
              at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
              at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
              at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
              at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
              at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
              at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
              at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
              at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
              at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
              at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
              at java.lang.Thread.run(Thread.java:662)
    Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.2.v20130315-93567e3): org.eclipse.persistence.exceptions.JPQLException
    Exception Description: Problem compiling [select model from IptUsers model where model.userCode= :propertyValue].
    [18, 26] The abstract schema type 'IptUsers' is unknown.
    [39, 53] The state field path 'model.userCode' cannot be resolved to a valid type.
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:150)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:339)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:270)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:157)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:138)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:112)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:98)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:82)
              at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1510)
              ... 38 more
    13:26:34,711 ERROR [[default]] Servlet.service() for servlet default threw exception
    java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Problem compiling [select model from IptUsers model where model.userCode= :propertyValue].
    [18, 26] The abstract schema type 'IptUsers' is unknown.
    [39, 53] The state field path 'model.userCode' cannot be resolved to a valid type.
              at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1512)
              at env.acegi.users.IptUsersDAO.findByProperty(IptUsersDAO.java:174)
              at env.acegi.users.IptUsersDAO.findByUserCode(IptUsersDAO.java:185)
              at env.acegi.security.AcegiAuthentication.loadUserByUsername(AcegiAuthentication.java:51)
              at org.acegisecurity.providers.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:99)
              at org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:122)
              at org.acegisecurity.providers.ProviderManager.doAuthentication(ProviderManager.java:200)
              at org.acegisecurity.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:47)
              at org.acegisecurity.ui.webapp.AuthenticationProcessingFilter.attemptAuthentication(AuthenticationProcessingFilter.java:74)
              at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:252)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.concurrent.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:95)
              at org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
              at org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
              at org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
              at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
              at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
              at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
              at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
              at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
              at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
              at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
              at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
              at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
              at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
              at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
              at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
              at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
              at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
              at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
              at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
              at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
              at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
              at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
              at java.lang.Thread.run(Thread.java:662)
    Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.4.2.v20130315-93567e3): org.eclipse.persistence.exceptions.JPQLException
    Exception Description: Problem compiling [select model from IptUsers model where model.userCode= :propertyValue].
    [18, 26] The abstract schema type 'IptUsers' is unknown.
    [39, 53] The state field path 'model.userCode' cannot be resolved to a valid type.
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:150)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:339)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:270)
              at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:157)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:138)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:112)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:98)
              at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:82)
              at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1510)
              ... 38 more
    In above error description....
    "INFO  [IportIBEntity] finding IptUsers instance with property: userCode, value: ADMIN"
    Here IportIBEntity is the persistence-unit of ProjectB.war, but IptUsers pojo have in ProjectA.war.
    So, it is trying to search the POJO in ProjectB.war instead of ProjectA.war
    Please help me to solve the problem....

    Hello,
    More information is required to help you, and as James suggested, the best option would be to move to EclipseLink instead of TopLink Essentials as EclipseLink is actively being developed and is the JPA 2 RI.
    Running it on the latest EclipseLink ensures that you are not hitting an issue that has already been fixed, and both are based off TopLink.
    Are you deploying an Ear or an exploded directory? If the later, can you try using an Ear?
    Best Regards,
    Chris

  • Spring and TopLink/JPA on OC4J 10.1.3.4.0

    Our configuration worked fine on OC4J 10.1.3.1 (linux) and 10.1.3.3 (windows). We have a problem with JPA (toplink essentials--not eclipselink) on OC4J 10.1.3.4.0 using Spring (2.0.7 and 2.5.6). We found that it was trying to connect to the default OracleDS data source(there were 2 connections in toplink essentials for some reason), but once we defined an OracleDS, it gave us this error:
    javax.servlet.ServletException: javax.faces.el.EvaluationException: Error getting property 'experiments' from bean of type gov.llnl.nif.dataviz.mssar.web.ExperimentListBean: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException:
    Exception Description: Cannot use an EntityTransaction while using JTA.
    Our persistence.xml looks like:
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.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_1_0.xsd">
         <persistence-unit name="mssar">
              <class>gov.llnl.nif.dataviz.mssar.model.ExperimentInfo</class>
              <class>gov.llnl.nif.dataviz.mssar.model.UsePlan</class>
         <properties>
         <property name="toplink.cache.shared.gov.llnl.nif.dataviz.mssar.model.ExperimentInfo" value="false"/>
         <property name="toplink.cache.shared.gov.llnl.nif.dataviz.mssar.model.UsePlan" value="false"/>
         </properties>
         </persistence-unit>
    </persistence>
    Our orm.xml looks like:
    <?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
    </entity-mappings>
    Our spring configuration looks like:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
         default-autowire="byName">
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
    <property name="showSql" value="true"/>
    <property name="databasePlatform" value="oracle.toplink.essentials.platform.database.oracle.OraclePlatform"/>
    </bean>
    </property>
    <property name="loadTimeWeaver">
         <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
    </bean>
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/SSARDS"/>
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
         <property name="dataSource" ref="dataSource" />
    </bean>
         <bean id="experimentsQueryBuilder" class="gov.llnl.nif.dataviz.mssar.dao.jpa.ExperimentsQueryBuilderJpa"/>
         <bean id="experimentsDao" class="gov.llnl.nif.dataviz.mssar.dao.jpa.ExperimentsDaoJpa"/>
         <bean id="experimentListManager" class="gov.llnl.nif.dataviz.mssar.service.impl.ExperimentListManagerImpl"/>
    </beans>
    ExperimentInfo.java mapping looks like:
    @Entity
    @Table(name = "EXPERIMENT_IDS")
    public class ExperimentInfo implements ExperimentInformation {
         @Id
         @Column(name="EXPERIMENT_ID")
         String experimentId;
         @Column(name="EXPERIMENT_DESCRIPTION")
         String expDescription;
         @Column(name="STATUS")
         String status;
         @Column(name="EXPERIMENT_PI")
         String expPI;
         //Date lpomDate;
         //Date settingsDate;
         @Column(name="LPOM_DATE")
         Timestamp lpomDate;
         @Column(name="SETTINGS_DATE")
         Timestamp settingsDate;     
    UsePlan.java looks like:
    @Entity
    @Table(name="USE_PLAN")
    public class UsePlan extends BasePlan implements PlanData, Serializable {
         static final long serialVersionUID = -1555327955428351924L;
         @Id
         @Column(name="EXP_SHOT_ID")
         String expShotId;
         @Id
         @Column(name="LOCATION")
         String location;
         @Id
         @Column(name="INFO_VAR")
         String infoVar;
         @Id
         @Column(name="USE_ITEM_NAME")
         String useItemName;
         @Column(name="USE_PRIORITY")
         String usePriority;
    ExperimentListManagerImpl looks like:
    @Transactional(readOnly=true)
    public class ExperimentListManagerImpl implements ExperimentListManager {
    This is a read-only app but it should not use the cache.
    Our Dao Looks like:
    public class ExperimentsDaoJpa extends JpaDaoSupport implements ExperimentsDao {
    private QueryBuilder experimentsQueryBuilder;
    public List<ExperimentInfo> shotsByQueryBean(ExperimentsQueryBean queryBean, String sortColumn, boolean ascending) {
         try {
              getJpaTemplate().flush();
              experimentsQueryBuilder.buildQuery(queryBean);
         experimentsQueryBuilder.setSortColumn(sortColumn, ascending);
         List<ExperimentInfo> result = getJpaTemplate().findByNamedParams(experimentsQueryBuilder.getQuery().toString(), experimentsQueryBuilder.getParams());
         // pull new results from database
         /*for (ExperimentInfo ei : result) {
              getJpaTemplate().refresh(ei);
         return result;
         } catch (Throwable t) {
              t.printStackTrace();
              return null;
         public void setExperimentsQueryBuilder(QueryBuilder experimentsQueryBuilder) {
              this.experimentsQueryBuilder = experimentsQueryBuilder;
    Thanks,
    John Carlson

    We also had this problem. We have changed the TransactionManager.
    Replace the JPATransactionManager with the JTATransactionManager.
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
    If you are using JTA you can't use the JPA Transaction Manager. It doesn't support JTA.
    Found it on a forum of Spring. (http://forum.springframework.org/showthread.php?t=48191)
    Dennis

  • Error lookup EntityManager on OC4J 10.1.3.1.0

    Hi,
    I've just upgraded my development environment from 10.1.3.0.0 to 10.1.3.1.0.
    I'm heaving trouble in this version when I try to lookup a JPA EntityManager using JNDI.
    I got following code fragment from the howto guides from 10.1.3.0, and they worked well on previous version:
    public EntityManager getEntityManager() {
    try {
    if (em == null) {
    em = (EntityManager) getContext().lookup("java:comp/ejb/EntityManager");
    } catch (NamingException e) {
    throw new RuntimeException(e);
    return em;
    However, when installed on 10.1.3.1 I got the following error message:
    06/08/22 07:23:10 java.lang.RuntimeException: javax.naming.NameNotFoundException: Default application EntityManager is not available; no deployed entities
    This didn't make much sence to me, as the log showed my entities being mapped at deployment. Just for verification, I've added a SessionBean to my code (It's not my intention to use session beans) and tried to access an EntityManager instance from this sessionbean, which I got using the @Resource anntotation. That worked fine, suggesting that my entities indeed did deploy.
    Is there any difference in how the EntityManager should be looked up from jndi, compared to the previous version? JNDI tree from the Enterprise Manager doesn't show any entitymanagers...
    Thanks for any help
    Bert

    Hello,
    One of the major differences for the EJB container between 10.1.3.0.0 and 10.1.3.1.0 is the fact that we move from the last draft of the EJB 3 specification to the final version of the specifications.
    So you can now use the @PersistenceContext to lookup the entity manager.
    The EJB 3.0 page has been updated and sample applications too, to reflect the change.
    Regards
    Tugdual Grall

  • JPA dynamic order by clause

    I need to dynamically build the order by clause of my query.
    I tried this:
    <named-query name="list">
      <query>
        <![CDATA[
          SELECT p FROM Person p
          ORDER BY :orderby
        ]]>
      </query>
    </named-query>
    @SuppressWarnings("unchecked")
    public List<Person> list(String sort) {
      Query query = getEntityManager().createNamedQuery("list");
      query.setParameter("orderby", sort);
      return query.getResultList();
    }But at runtime it throws an exception:
    com.microsoft.sqlserver.jdbc.SQLServerException:
    L'elemento SELECT identificato da ORDER BY 1 include una variabile nell'espressione che identifica la posizione di una colonna.
    Le variabili sono consentite solo nell'ordinamento in base a un'espressione che fa riferimento a un nome di colonna.The translation of the italian message is something like:
    The SELECT element identified by ORDER BY 1 includes a variable that identifies the position of a column.
    The valid variables in the order by clause must refer to the name of a columnThe value of the parameter sort is_ the name of a column!
    Any hint?

    My solution was to append the order clause to an "namedQuery" like this:
    - declare the named query as usual, with annotation
    - create a simple helper function like findNamedQuery to find the query string for a given class and queryName (using reflection)
    - if you need to execute the query without sort order - use EntityManager.createNamedQuery (as usual)
    - BUT: if you want to sort data: use EntityManager.createQuery with the string obtained from findNamedQuery and the sort clause
    I guess the is a performance penalty, but.. .it works.

  • EntityManager no longer being injected after upgrade

    I upgraded the version of JSF being used by the Sun Java Application Server 9 to 1.2_02 by using the upgrade jar on the download site. After doing this, it appears that the JPA EntityManager is no longer being injected (I keep getting a NullPointer exception in the Controller's getEntityManager method).
    Is there something I have to do differently with 1.2 to get the EntityManager injected?
    cheers.

    Yes. Please see this thread:
    http://forums.java.net/jive/thread.jspa?threadID=17933&tstart=15

Maybe you are looking for