Jpql, join on?

a simplified example:
i have two tables, dog and cat, there are not foreign key reference between them. i use openJPA to implement jpa mapping, and two entities are generated: Catty and Doggy. and there are not reference between these two objects too.
but in my app, i want to implement join query. something like following in NATIVE SQL:
select from dog d join cat c on d.age = c.age.*
it works on my db2.
so i use jpql like following:
SELECT d FROM Doggy d JOIN Catty c ON d.age = c.age.
unfortunately, the jpql throw exception. similar with following:
org.apache.openjpa.persistence.ArgumentException: Encountered "JOIN Catty c" at character xx, but expected: [".", "FETCH", "INNER", "JOIN", "LEFT", <IDENTIFIER>].
question:
1 what is the problem of my jpql?
2 while i use join in jpql, is it mandatory to define a reference attribute to other object in first object?
3 does jpql support "ON" key word. i have checked jpql manual, it seem it is not preserved?
thanks

On is not supported. You should have posted your relationship definititions as well. you have have Collection<Cat> in the Dog entity?
i.e INNER JOIN is done on relationships. Otherwise you are stuck with the theta join
SELECT d FROM Doggy d, Cat c WHERE d.age = c.age

Similar Messages

  • Eclipselink producing incorrect sql - ORA-00918: column ambiguously defined

    We have a table with many columns .A1 .A2 .A3.... .A125 .N1 .N2 .N3... .N95 and with a simple jpql join it comes up with 2 columns that are ...AS N1150 and causing an ambiguous column error ...
    Does any one know of a valid workround or if this is a known bug. No problems were present in toplink, just eclipselink....
    it appears to be doing a count and suffixing the count to the column name to make sure the columns have unique id's - but failing:
    K1 -> K1 _1_
    N41 -> N41 _2_
    N11 -> N11 _50_
    ... then 100 columns later
    N1 -> N1 _150_
    the jpql is :
    @NamedQuery(name=NamedQueryNames.XREF_IMPORT_SELECT,
                   query="SELECT t FROM Tran t, Xref x "+
                   " WHERE t.key = x.a1 "+
                   " AND x.key.k1 = :partial "+
                   " AND x.key.k2 LIKE :partialX " +
                   " ORDER BY x.key.k2")
    Tran has fields k1,k2, a1, a2...a125, n1, n2...n95
    xref has k1,k2,a1,a2..a5, n1,n2,n3
    the sql eclipse link produces for the query is :
    SELECT *
    FROM
    (SELECT
    /*+ FIRSTROWS */
    a.*,
    ROWNUM rnum
    FROM
    (SELECT t1.K1 AS K11,
    t1.N41 AS N412,
    t1.N40 AS N403,
    t1.N45 AS N454,
    t1.N44 AS N445,
    t1.A120 AS A1206,
    t1.N43 AS N437,
    t1.A121 AS A1218,
    t1.N42 AS N429,
    etc
    t1.N25 AS N2547,
    t1.N10 AS N1048,
    t1.N12 AS N1249,
    t1.N11 AS N1150,
    t1.N17 AS N1751,
    a load more columns
    t1.A65 AS A65147,
    t1.A68 AS A68148,
    t1.A67 AS A67149,
    t1.N1 AS N1150,
    t1.A41 AS A41151,
    t1.N5 AS N5152,
    etc
    FROM COREXFA t0,
    CORETRA t1
    WHERE (((t1.K1 = t0.A1)
    AND (t0.K1 = ?))
    AND (t0.K2 LIKE ?))
    ORDER BY t0.K2 ASC
    ) a
    WHERE ROWNUM <= ?
    WHERE rnum > ?

    This issue is cause by the aliasing done because you are using firstResult/maxResult. I think there is already a bug logged for this issue, please vote for the bug.
    See,
    http://old.nabble.com/Duplicate-aliases-generated-for-columns-%281.1.3%29-td28039552.html
    Some workarounds would be,
    - avoid using firstResult/maxResult
    - rename the columns
    - use native SQL
    - use a cursor query instead of firstResult/maxResult
    James : http://www.eclipselink.org

  • JPQL LEFT JOIN FETCH Results in NPE when DescriptorCustomizer in Place

    I have a unidirectional one-to-many mapping between the following two entities:
    @Entity
    @Table(name="INVC_CNTRL")
    public class InvoiceControl implements Serializable {
        @Id
        @Column(name="INVC_CNTRL_ID")
        private Long invoiceControlId = null;
        @OneToMany(fetch = FetchType.LAZY)
        private List userDefineds;
    @Entity
    @Table(name="USER_DEFINED")
    public class UserDefined implements Serializable {
        @Column(name="USER_DEFINED_TABLE")
        private java.lang.String userDefinedTable;
        @Column(name="USER_DEFINED_FK")
        private long userDefinedForeignKey;
    I wrote the following DescriptorCustomizer to address a constant JoinColumn value:
            ManyToManyMapping mapping = (ManyToManyMapping) descriptor.getMappingForAttributeName("userDefineds");
            if (null != mapping) {
                String tableName = descriptor.getTableName();
                String primaryKey = descriptor.getPrimaryKeyFields().get(0).getName();
                ExpressionBuilder builder = new ExpressionBuilder(mapping.getReferenceClass());
                mapping.setSelectionCriteria(builder.getField("USER_DEFINED_FK").equal(builder.getParameter(primaryKey))
                    .and(builder.getField("USER_DEFINED_TABLE").equal(tableName)));
    This works as expected with JPQL "select a from InvoiceControl a join fetch a.userDefineds" but when I change the "join fetch" to "left join fetch", I get the following NPE:
    Caused by: java.lang.NullPointerException
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.appendFromClauseForOuterJoin(SQLSelectStatement.java:403)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.appendFromClauseToWriter(SQLSelectStatement.java:521)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.printSQL(SQLSelectStatement.java:1679)
         at org.eclipse.persistence.internal.databaseaccess.DatabasePlatform.printSQLSelectStatement(DatabasePlatform.java:3178)
         at org.eclipse.persistence.platform.database.OraclePlatform.printSQLSelectStatement(OraclePlatform.java:932)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.buildCall(SQLSelectStatement.java:782)
         at org.eclipse.persistence.internal.expressions.SQLSelectStatement.buildCall(SQLSelectStatement.java:792)
         at org.eclipse.persistence.descriptors.ClassDescriptor.buildCallFromStatement(ClassDescriptor.java:813)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.setCallFromStatement(StatementQueryMechanism.java:390)
         at org.eclipse.persistence.internal.queries.StatementQueryMechanism.prepareSelectAllRows(StatementQueryMechanism.java:315)
         at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareSelectAllRows(ExpressionQueryMechanism.java:1721)
         at org.eclipse.persistence.queries.ReadAllQuery.prepareSelectAllRows(ReadAllQuery.java:813)
         at org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:744)
         at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:661)
         ... 8 more
    Inspecting the 2.5.1 source, this suggests relationAlias is null.
    I've tried a number of things to no avail. If I disable the DescriptorCustomizor and instead add a @JoinColumn on the OneToMany defining half of the join, it works. Of course the result is incorrect because it's failing to discriminate by the table name.
    Is this a bug or am I making another JPA noob mistake?
    Thanks.

    I was able to get similar behaviour doing similar JPQL. I have entered a bug in TopLink Essentials. 2465.
    I did note that having the objects in memory made a significant difference (< .5 seconds for 1000 objects, each with 2 in the 1:M).

  • JPQL HOWTO:  "join" entities without foreign/primary keys?

    I have entities Person and Representative.
    Entity Person has fields lastName, firstName and patronymic.
    Entity Representative has field named title.
    The task is:
    Select all Persons and Representatives where representative.title contains Person.firstName, Person.lastName and person.patronymic.
    Person can have several representatives.
    Person and Representative don't have any keys. Is it possible to do it using JPQL or it's better to use native sql query?

    I've tried something like this one:
    public class PersonAndRepresentatives {
         private Person person;
         private List<Representative> representatives;
    //my query:
                    StringBuilder sb = new StringBuilder();
                 sb.append("select new model.stateless.helperobject.PersonAndRepresentatives(p, repr) from Person p, Representative repr");
              sb.append(" where repr.title like p.firstName and repr.title like p.lastName");
              sb.append(" group by person.id");
              List<PersonAndRepresentatives> resultList = em.createQuery(sb.toString()).getResultList();But of course, I get exception on "*,*" which is here: "*from Person p, Representative repr*".
    What can I do?
    Seems like it's better to write native query and do not try to solve the problem using JPQL.

  • Joins and Outer joins

    Sorry for being a newbie!
    I was using JPQL to grab data from one table that requires an outer join to another table.
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!

    osubb wrote:
    Sorry for being a newbie!Everybody starts out with less knowledge than others, no need to apologize for that.
    >
    I was using JPQL to grab data from one table that requires an outer join to another table.Okay.
    >
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!Generally you do these kind of mappings through the Entities. For example, you can have a OneToMany / ManyToOne mapping between the two entities. Check out the Toplink reference guide for some examples on how to do this:
    [http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#ManyToOne|toplink JPA annotations reference]
    Even if you are not using Toplink, this is the same for all persistence providers.

  • JDBC and outer joins

    What is the correct syntax for an outer join using JDBC. A statement such as the following is returned with an illegal char. error:
    select x.value, y.value from x_table x, y_table y
    where x.id = y.id(+);     
    I'm using oracle 8i and the thin client driver.
    Thanks

    osubb wrote:
    Sorry for being a newbie!Everybody starts out with less knowledge than others, no need to apologize for that.
    >
    I was using JPQL to grab data from one table that requires an outer join to another table.Okay.
    >
    I thought I could do this:
    select a.f1,a.f2,b.f3 from A a LEFT OUTER JOIN B b
    where a.id = b.id and
    a.match = b.match;
    A and B are entities and I need to join with two columns. Can someone please tell me what I'm doing wrong.
    Thanks!Generally you do these kind of mappings through the Entities. For example, you can have a OneToMany / ManyToOne mapping between the two entities. Check out the Toplink reference guide for some examples on how to do this:
    [http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html#ManyToOne|toplink JPA annotations reference]
    Even if you are not using Toplink, this is the same for all persistence providers.

  • JPQL, error when using constructor in query

    I have such query:
    sb.append("select new ibs.parliament.model.stateless.cd.helperobject.PersonWithAccessCount(p, sum(personCounters.count))");
    sb.append(" from Person p left join p.counter personCounters where personCounters.date>= :startPeriodDate and  personCounters.date<= :endPeriodDate");
    sb.append(" group by p.id");PersonWithAccessCount has fields for Person and count for sum result.
    @Entity
    public class Person{
        @OrderBy("date")
        @ManyToMany(fetch=FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy="person")
        private List<PersonAccessCounter> counter;
    //other fields, getters and setters
    @Entity
    public class PersonAccessCounter {
         @Id
          @ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.ALL})
         private Person person;
         @Id
         private Date date;
         private long count;
    //other fields, getters and setters
    public class PersonWithAccessCount implements Comparable<PersonWithAccessCount>{
         private Person person;
         private long count;
    //getters and setters
    }I get such error:
    org.apache.openjpa.kernel.jpql.ParseException: There is "," in symbol 82, but expected: ["."].
    82 is here: (p*,* sum(personCounters.count))
    What does it mean? Why this error happens, please, tell me.

    My query is:
            sb.append("select new ibs.parliament.model.stateless.cd.helperobject.PersonWithAccessCount(personCounters.person, sum(personCounters.count))");
         sb.append(" from PersonAccessCounter personCounters where personCounters.date>= :startPeriodDate and  personCounters.date<= :endPeriodDate");
         sb.append(" group by personCounters.person");I get this error:
    >
    Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: DB2 SQL Error: SQLCODE=-134, SQLSTATE=42907, SQLERRMC=BIOGRAPHY, DRIVER=3.50.152 {prepstmnt 1306676706
    SELECT t1.id, t1.accessCounter, t1.biography, t1.birthdayDate,
            t1.firstLetter, t1.firstName, t1.lastName, t1.lastUpdateDate,
            t1.medialogyUid, t1.patronymic, t1.portrait_id, t1.sourceUri,
            SUM(t0.count)
        FROM Parliament.PersonAccessCounter t0 INNER JOIN Parliament.Person t1
            ON t0.person_id = t1.id
        WHERE (t0.date >= ? AND t0.date <= ?) GROUP BY t1.id, t1.accessCounter,
            t1.biography, t1.birthdayDate, t1.firstLetter, t1.firstName,
            t1.lastName, t1.lastUpdateDate, t1.medialogyUid, t1.patronymic,
            t1.portrait_id, t1.sourceUri FETCH FIRST 10 ROWS ONLY
    [params=(Timestamp) 1988-10-15 17:19:16.734, (Timestamp) 2008-10-15 17:19:16.734]} [code=-134, state=42907]
    >
    This is problem field "biography".
            @Lob
         @Basic(fetch=FetchType.LAZY)
         @Column(nullable=false, length=100000)
         private String biography;I've annotated it as "LAZY field". Now, I'll try to make a query...(
    I've found this:
    SQL Reference for usage of VARCHARs greater than 255 bytes:
    A VARCHAR string with a maximum length that is greater
    than 255 bytes or any CLOB string is a Long String.
    Following indicates the contexts in which long strings cannot be referenced.
    A GROUP BY clause
    An ORDER BY clause
    A CREATE INDEX statement
    A SELECT DISTINCT statement
    A subselect of a UNION without the ALL keyword

  • How do I join with native SQL?

    I'm just starting to dip my toes in Toplink/Eclipselink using jDeveloper 11g. I've got a database schema that looks like this:
    Organization > Site > Program / MhProgram
    Every program and MhProgram has a site_id, and every site has an organization_id.
    The POJO objects wizards seems to have set the relationships up correctly and I'm able to pull out Organization objects that have siteCollections and the sites have programCollections and MhProgramCollections. The part where I'm having trouble is pulling out organizations the way I'd like to.
    I'm querying them with this SQL:
    select o.*
    from organization o,
    site s,
    program p
    where o.organization_id = s.organization_id
    and s.site_id = p.site_id
    and s.site_number = 1
    and p.program_name = "Test Name"
    The problem seems to be that Toplink isn't actually recognizing that I want to do these joins. Its grabbing an organization and then doing SQL to separately get each site, then each program. During this process SQL like s.site_number = 1 is ignored. This leaves me with siteCollections and programCollections that are just raw unfiltered rows. I've tried the same with JPQL and I'm having no luck there either.
    Am I missing something with the Native SQL support?
    Edited by: user519677 on May 5, 2009 5:32 AM

    The code is below. Its just a test client until I can get it working. When I put the word FETCH beside the INNER JOIN in the JPQL I get the following exception:
    Exception Description: Syntax error parsing the query [select o from Organization o INNER JOIN FETCH o.siteCollection s where s.siteNumber = 1 ], line 1, column 63: syntax error at [s].
    Internal Exception: MismatchedTokenException(66!=-1)
    Code:
    Project project = XMLProjectReader.read("META-INF/tlMap.xml", Thread.currentThread().getContextClassLoader());
    DatabaseSession session = project.createDatabaseSession();
    session.shouldLogMessages();
    session.login();
    session.setLogLevel(org.eclipse.persistence.logging.SessionLog.FINE);
    ReadAllQuery query = new ReadAllQuery(Organization.class);
    String EJBQuery = "select o from Organization o " +
    "INNER JOIN o.siteCollection s " +
    "where s.siteNumber = 1 ";
    query.setEJBQLString(EJBQuery);
    Collection<Organization> results = (Collection<Organization>) session.executeQuery(query);
    Edited by: user519677 on May 5, 2009 6:31 AM

  • Questions about JPQL in Netweaver 7.1

    Hello forum.
    During the last weeks we tried to migrate a JEE 5 application to SAP Netweaver 7.1.  We encountered quite a few unexpected problems, most of which were related to JPQL queries.
    This is the entity structure which we were (and still are) unable to query (simplified pseudo code):
    @Entity
    class S
       @Id
       @GeneratedValue
       int id;
    @Embeddable
    class E
       @ManyToOne // unidirectional
       S s;
    @Entity
    class M
       @Id
       @GeneratedValue
       int id;
       @Embedded
       E e;
    What we need is a query for all Ms related to a collection of Ss:
    select m from M m where m.e.s.id in (:sids) and ...
    The Parameter :sids is set to a HashSet<Integer>.
    This seemed to be a few levels too complex for the JPQL interpreter (some error message about s being of unknown type and not having an attribute id ), so we abandoned the Embeddable E and put its members directly into the respective entities, one of them being S.  Is this a shortcoming of SAPs JPQL implementation or did i miss something?
    With S being a direct member of M, the JPQL interpreter at least knew about member s being of type S and having an attribute id.  However, it did not accept the parameter being a Collection, but instead expected a single Integer.  I seem to have read here in the forum, that the in operator should be usable with collections, but we never managed to get this working, neither here nor in a simpler case where we needed to fetch all entities S with having an enum attribute in a set of values:
    enum Q {... }
    @Entity
    class S
       Q q;
    "select s from S s where s.q in (:qs)"
    with :qs set to a Set<Q>.  Changing the parameter to an ArrayList didn't help any further, either.
    Does this mean, that collection parameters are unsupported (which would render the in operator rather useless)?
    Regards
    - Thomas

    Hi Thomas,
    in JPA 1.0, the IN expression in WHERE clauses does only support subqueries or comma separated lists of literals / input parameters.
    Here is the syntax of the JPA (see section 4.6.8 of "JSR 220: Enterprise JavaBeansTM,Version 3.0
    Java Persistence API"
    in_expression ::=
    state_field_path_expression [NOT] IN ( in_item {, in_item}* | subquery)
    in_item ::= literal | input_parameter
    So you may have to translate your HashSet of Integer in a comma separated list when building the query - not nice but it works.
    There is another (strange) IN in JPQL 1.0:  the IN operator that can be used to simplify JOINs on collections, but this IN has nothing to do with WHERE clauses. Maybe you mix the two (see section 4.4.6) example for this:
    SELECT DISTINCT o
    FROM Order o, IN(o.lineItems) l
    WHERE l.product.productType = u2018office_suppliesu2019
    Maybe what you try works with JPA 2.0, I am not sure.
    Regards,
    - Rolf

  • JPA Criteria : LEFT JOIN with an AND condition

    Hi all,
    I have a question regarding JPA criteria.
    Here is my JPA query :
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
    Root<Email> emailRoot = criteriaQuery.from(Email.class);
    criteriaQuery.distinct(true);
    Predicate globalCondition = criteriaBuilder.equal(emailRoot.get(Email_.type), EmailType.in);
    Predicate responseMandatoryCondition = criteriaBuilder.equal(emailRoot.get(Email_.responseMandatory), true);
    Predicate typeCondition = criteriaBuilder.notEqual(emailRoot.join(Email_.emailsOut, JoinType.LEFT).get(Email_.responseType),ResponseType.response);
    globalCondition = criteriaBuilder.and(globalCondition, responseMandatoryCondition);
    globalCondition = criteriaBuilder.and(globalCondition, typeCondition);
    em.createQuery(mainCriteria.where(globalCondition)).getSingleResult();
    Here is the result of this query :
    SELECT DISTINCT email0_.ID AS col_0_0_
    FROM EMAIL email0_
    LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN
    WHERE email0_.TYPE = 'in'
    AND email0_.RESPONSE_MANDATORY = true
    AND emailso1_.RESPONSE_TYPE <> 'response'
    LIMIT 0 , 30
    And here is the request I needed :
    SELECT DISTINCT email0_.ID AS col_0_0_
    FROM EMAIL email0_
    LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN AND emailso1_.RESPONSE_TYPE <> 'response'
    WHERE email0_.TYPE = 'in'
    AND email0_.RESPONSE_MANDATORY = true
    LIMIT 0 , 30
    As you can see I need to check if the RESPONSE_TYPE is equals on the same line that the LEFT OUTER JOIN. Does anybody know how to write such an JPA criteria query ?
    Thanks ,
    Louis
    Edited by: user13105928 on 17 févr. 2011 03:06

    You cannot define an ON clause with Criteria, nor JPQL.
    Perhaps you can reword the query to avoid needing an ON clause.
    What is the query you want to do (in english)?
    Can you just use an OR in the where clause?
    There is a enhancement request to have ON clause support added, please vote for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
    James : http://www.eclipselink.org

  • JPA OnetoMany  QUERY LEFT JOIN BUG

    Using JPA in JDev 10.1.3.1.0.3984
    Database: Firebird 1.51LI-V1.5.3.4870 Firebird 1.5/tcp
    Driver: Jaybird JCA/JDBC driver Version: 2.1
    TopLink, version: Oracle TopLink Essentials - 2006.8 (Build 060829)
    If I use normal JOIN it works.
    On LEFT JOIN I get a {oj [/b] before the table name and a [b]} at the end.
    public class Cliente{
        @OneToMany(mappedBy = "cliente")
        @JoinColumn(name = "CDCLIENTE", referencedColumnName = "CDCLIENTEREQUISITANTE")
        private List<Requisicao> requisicoes;
    public class Requisicao
        @ManyToOne
        @JoinColumn(name = "CDCLIENTEREQUISITANTE", referencedColumnName = "CDCLIENTE")
        private Cliente cliente;
    EntityManager em = getEntityManager();
    String sql = "SELECT c FROM Cliente c LEFT JOIN c.requisicoes req";
    Query q = em.createQuery(sql);
    List rs = q.getResultList();Result SQL:
    SELECT DISTINCT t0. <OMITTED> FROM {oj [/b]CLIENTE t0 LEFT OUTER JOIN REQUISICAO t1 ON (t1.CDCLIENTEREQUISITANTE = t0.CDCLIENTE)[b]}

    You cannot define an ON clause with Criteria, nor JPQL.
    Perhaps you can reword the query to avoid needing an ON clause.
    What is the query you want to do (in english)?
    Can you just use an OR in the where clause?
    There is a enhancement request to have ON clause support added, please vote for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
    James : http://www.eclipselink.org

  • JPA and LEFT JOIN

    I have a very basic question related to JPA.
    I am using dict tables and connecting it to MaxDB.
    In my Entity I have a select statement like this,
    @NamedQuery  (name = "getOperations", query = "SELECT operT.id FROM SII_ARC_Oper operT " +
                   "LEFT JOIN SII_ARC_Service serviceT " +
                   "ON   operT.sid = serviceT.sid AND " +
                   "serviceT.duuid =:duuid")
    When I call this in my Bean, I get this error,
    An error occurred processing the named query >>getOperations<< with the query string >>SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid<<. The exception text is: line 1: Variable 'SII_ARC_Service' not declared
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid
                                                      ^
    line 1: unexpected token: serviceT
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid
    I am just wondering how do I declare the u201CSII_ARC_Serviceu201D in my Entity before the Named Query. Or am I not declaring anything else..?
    Thanks
    Domnic
    Edited by: domnic savio on Jul 21, 2008 12:16 PM

    I have some improvements now although the problem is not solved yet,
    I have the JPQL as
    // The Named Query
    @NamedQuery  (name = "getOperations", query = "SELECT oper.id FROM SII_ARC_Oper oper " +
                   "LEFT JOIN oper.service serviceT " +
                   "WHERE serviceT.duuid =:duuid")
    // The many to one relationship
    @Column(name= "SERVICE_TABLE")
         @ManyToOne(targetEntity=com.sap.sii.archeiver.SII_ARC_Service.class)
         @JoinColumn(referencedColumnName = "SID")
         private SII_ARC_Service service;
    On calling the NamedQuery and passing a parameter, I get the error,
    Errors have occurred during the precompilation of named queries:
    An error occurred processing the named query >>getOperations<< with the query string >>SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN operT.service serviceT WHERE serviceT.duuid =:duuid<<. The exception text is: line 1: Path 'opert.service' is not association path.
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN operT.service serviceT WHERE serviceT.duuid =:duuid
    1) What association path does the compiler refer too !?!.
    2) Is the JPQL Querry valid without an ON clause ?!.
    anyone has an idea..!?!
    thanks in advance
    Domnic

  • Left join query prob

    Hi,
    I have one ejbql for selecting records from one table which are not in the other table.There is actually records in the data base but by using this query it is retrieving noting . The corresponding pl/sql query is working fine and it is retrieve correct result .what is wrong with my query.. Plz help me to correct this query...
    My ejbql is below...
    EJB-QL
    SELECT C.name FROM person C LEFT JOIN C.address FC WHERE C.id.name= FC.id.name AND FC.id.pcode IS NULL
    There is no result while executing this query. The correspoinding pl sql query is
    PL/SQL
    SELECT e_person .* FROM e_person ep LEFT JOIN e_address ea ON ep .name= ea .name WHERE ea.pcode IS NULL
    plz help ...
    Thanks in advance
    Ani

    Enable logging and include the SQL generated for the JPQL.
    JPQL will also join via the primary/foreign key define in the mapping when you do C.address, if this is not name then you may be joining by something else. You could just declare the Address independent of the Employee if you do not wish to join by primary key (although this seems odd).
    -- James : http://www.eclipselink.org

  • JPQL Query for specific usecase, help needed

    Does anyone knows how to write the JPQL query for this specific use case.
    Take 3 tables,
    Table 1 contains bids for many auctions (Bid table)
    Table 2 Contains many auctions (Auction Table)
    Table 3 contains many users (User Table)
    I need a query to retrieve all the highest bids per auction for a particular user.
    For example if the user has bidded on 10 auctions., but for each auctions has placed 3 bids each. Following the query, I would expect to get 10 bids back, each being the highest per auction.
    A Bid has a bid value that can be used for filtering.
    Thanks
    Peter

    It would be something like the JPQL version of 'select * from bids join auctions using (auction_id) where bids.userid = ? group by auctions.auction_id order by bids.amount desc'. But this is primarily an SQL question, and only secondarily a question as to how to translate that into JPQL, which should be straightforward.

  • JPQL: FETCH and navigate through a @OneToMany relationship at the same time

    Hello!
    I have three entities A-->B-->C, where the arrows denote @OneToMany relationships. I would like to form a query that returns A objects and prefetches all associated B and C objects. Is this achievable in JPQL?
    My failed attempts were (I'm using EclipseLink):
    1.
    SELECT a FROM A a LEFT JOIN FETCH a.b LEFT JOIN FETCH a.b.c WHERE condition;
    This fails with an error: "cannot navigate collection valued association field "
    2.
    SELECT a FROM A a LEFT JOIN FETCH a.b AS b LEFT JOIN FETCH b.c WHERE condition;
    This fails with "syntax error at [AS]"
    3.
    SELECT a FROM A a LEFT JOIN FETCH a.b LEFT JOIN a.b AS b LEFT JOIN FETCH b.c WHERE condition;
    This query succeeds, but does not prefetch the C objects.

    OK, the answer is negative - it is not supported in JPQL.
    But it should be achievable with EclipseLink-specific @QueryHint LEFT_FETCH
    http://www.eclipse.org/eclipselink/api/1.1/org/eclipse/persistence/config/QueryHints.html#LEFT_FETCH
    Unfortunately I get an exception when I use those hints, but that is probably an EclipseLink problem.
    java.lang.IllegalArgumentException: fromIndex(18) > toIndex(12)
         at org.eclipse.persistence.internal.helper.NonSynchronizedSubVector.<init>(NonSynchronizedSubVector.java:32)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.trimRowForJoin(ForeignReferenceMapping.java:1685)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.trimRowForJoin(ForeignReferenceMapping.java:1657)
         at org.eclipse.persistence.mappings.OneToOneMapping.valueFromRowInternalWithJoin(OneToOneMapping.java:1523)
         at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1532)
         ...

Maybe you are looking for