JPQL Problem!!

Hi,
I'have a JPQL-JPA problem.
When I run a JPQL Query like:
"SELECT x FROM User x WHERE x.association.idAssociation = 1 OR x.customer.association.idAssociation = 1"
Then, My "JPA Toplink Essentials" library generates a SQL Query like this:
"SELECT t0.id_user, t0.descripcion, t0.last_access, t0.password, t0.estado, t0.surname, t0.username, t0.movil, t0.name, t0.telefono,
t0.email, t0.id_customer, t0.id_society, t0.id_association, t0.id_language, t0.id_shop, t0.id_group
FROM customers t3, associations t2,associations t1, users t0
WHERE (((t1.id_association = ?) OR (t2.id_association= ?))
AND (((t1.id_association = t0.id_association) AND (t3.id_customer = t0.id_customer))
AND (t2.id_association = t3.id_association)))
There's a problem....near FROM clausule....table "associations" is repeated 2 times. Whhy?
These are my entities;
@Entity
@Table(name = "users")
public class User implements Serializable
     @Id
     @GeneratedValue(strategy=GenerationType.SEQUENCE)
     @Column(name = "id_user")
     private int id_user;
     @ManyToOne(fetch = FetchType.LAZY)
     @JoinColumn(name = "id_association")
     private Association association;
     @ManyToOne(fetch = FetchType.LAZY)
     @JoinColumn(name = "id_customer")
     private Customer customer;
@Entity
@Table(name = "associations")
public class Association implements Serializable
     @Id
     @GeneratedValue(strategy=GenerationType.SEQUENCE)
     @Column(name="id_association")
     private short idAssociation;
     @OneToMany(fetch = FetchType.LAZY, mappedBy = "association", cascade = CascadeType.ALL)
     @JoinColumn(name = "id_association")
     private List<User> users;
@Entity
@Table(name = "customers")
public class Customer implements Serializable
     @Id
     @GeneratedValue(strategy=GenerationType.SEQUENCE)
     @Column(name="id_customer")
     private int idCustomer;
     @OneToMany(fetch = FetchType.LAZY, mappedBy = "customer", cascade = CascadeType.ALL)
     @JoinColumn(name = "id_customer")
     private List<User> users;
Thanks in advance,

I tried in one of my Employee examples using both:
SELECT e FROM Employee e WHERE e.address.city = 'Ottawa' OR e.address.city = 'Toronto'
and
SELECT e FROM Employee e JOIN e.address a WHERE a.city = 'Ottawa' OR a.city = 'Toronto'
In EclipseLink 1.0 both of these result in the same SQL. This may have been fixed in later versions of TopLink Essentials. Does the second approach of using the single JOIN fix your issue?
Doug

Similar Messages

  • JPQL: problem creating it dynamically

    I am building a JPQL String dynamically such that the entity requested and the criteria for the search will determine what the JPQL String will be. Example is like this
            BaseQueryBuilder builder = new AnnuityPolicyQueryBuilder();
            builder.setSexCd("M");
            builder.setLastName("a", WCString.LIKE);
            builder.setStatus("I");this piece of code should create a Query object with the JPQL string
    SELECT o FROM AnnuityPolicy o WHERE o.status = :status AND o.lastName LIKE :lastName AND o.sexCd = :sexCdwhen I begin to dynamically set the parameter, an IllegalArgumentException is thrown like this:
    Exception in thread "main" java.lang.IllegalArgumentException: You have attempted to set a parameter value using a name of :sexCd that does not exist in the query string SELECT o FROM AnnuityPolicy o WHERE o.status = :status AND o.lastName LIKE :lastName AND o.sexCd = :sexCd.
            at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:614)
            at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:161)
            at com.leadway.util.eao.QueryBuilderUtil.buildQuery(QueryBuilderUtil.java:77)
            at com.mck.practical.eao.test.AnnuityPolicyEAO.findPolicies(AnnuityPolicyEAO.java:61)what could be wrong with this design. If I copy the same JPQ into the createQuery() method, it works fine and smooth.
    Regards,
    Michael

    There should be no need for you to access the internals of the EnityManager to have a query parsed correctly. It should just work as is. Can you please provide the snipit of code that sets the parameter. Based on the exception you are getting it appears that James' suggestion is the problem. Please verify that you are calling setParameter("_*sexCd*_", Object) and not setParameter("_*:sexCd*_", Object);
    If you are sure that you are not including the colon ( _:_ ) when setting the parameter verify, if you are using named queries, that the query you are getting is the query you expect.
    If these prove to not be the problem and you are sure it is an activeSession issue can you provide information on your application and the state of the EM. Are you using containerManaged Entity Managers or Application Managed. Is your application in a container or Java SE? Is the EM in a transaction?
    --Gordon ( www.eclipselink.org )                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JPQL problem with Date

    Hi,
    I have a JPQL like..
    select o from objectClass o where o.dateField : P_DATE
    And the query don't returns nothing.
    The types of variables are java.sql.Date, my _DB is Oracle 10.
    If I look the server console i get the transformed SQL, someting like
    SELECT * FROM tableMapping t WHERE t.dateField = ?
    If I put a TRUNC in my parameter, its works fine.
    So.. How make this in my JPQL?
    Any Idea

    Some of these other options may also work:
    *) If you don't need the time component persisted on inserts/updates, then ensure that the date in the table is truncated:
    If using INSERT DML, then it would look like:
    INSERT INTO ...(..., <DATE_COLUMN>, ...)
    VALUES (..., TRUNC(<DATE_VALUE>), ...).
    If using UPDATE DML, then it should look like:
    UPDATE ...
    SET ..., <DATE_COLUMN> = TRUNC(<DATE_VALUE>), ...
    If using EJB merge or persist, then it would look like:
    TMorosidadAclaracion acl = new TMorosidadAclaracion();
    java.sql.Date dateValue = ...;
    <Truncate dateValue Here>
    acl.setMoaFecpago(dateValue);
    em.persist(acl); // Or em.merge(acl) if merging.
    *) If you need the time component persisted on inserts/updates, then native queries are another option. With a native query, you can use the TRUNC function.
    *) If you need the time component persisted on inserts/updates, then querying with a view is another option; in your view, you would use "TRUNC(<DATE_VALUE>)" instead of just "<DATE_VALUE>". In my system, I have created entities that point to views for query purposes.

  • JPQL query problem

    Hi, I'm working in a J2EE project with entity beans. I have two Entities: EntityProject and EntityUser, inside EntityProject there is a reational field:
        @JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID")
        @ManyToOne
        private EntityUser userId;
    The problem is when I try to create a query using the Entity Manager like this:
    [em is the EntityManager]
    Query qry = em.createQuery("SELECT e FROM EntityProject e  ORDER BY  e.userId.firstName ASC ");
    List entityResult = qry.getResultList();
    The exception is:
    SQLMapper has encountered a field firstName of type EntityUser as an order by item, but this bean field is not reflected in the select list. The field is mapped to FIRST_NAME of table { qualifier = null, name = TBL_USER_MASTER, hashcode = 1776325173 } and is expected with the display name ALIAS_1_FIRST_NAME in the select list.
    I was able to make this kind of queries on netbeans and hibernate, but in netweaver are not working.
    any idea?

    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).

  • Problem with timestamp in query

    I have problem with timestamp in JPA query.
    I wonna select all data from database where difference between two timestamps is more than 3 month.
    Database:
    ID timestamp1 timestamp2
    1 20008-11-19 15:02000 20008-08-19 15:02000
    2 20008-11-19 15:02000 20008-11-14 15:02000
    @Column(name = "timestamp1", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp1;
    @Column(name = "timestamp2", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp2;
    sql query works:
    select id from table where
    MONTH( DATE(timestamp1) - DATE(timestamp2) ) > 3
    but how I can write in Java?
    I't doesnt wrk:
    Query query = em.createQuery("SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3 ")
    error:
    ExceptionUtil E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method .
    Exception data: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter 'SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3'.
    Error message: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.kernel.jpql.ParseException: Encountered "MONTH (" at character 438, but expected: ["(", "+", "-", ".", ":", "", "=", "?", "ABS", "ALL", "AND", "ANY", "AS", "ASC", "AVG", "BETWEEN", "BOTH", "BY", "CONCAT", "COUNT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DELETE", "DESC", "DISTINCT", "EMPTY", "ESCAPE", "EXISTS", "FETCH", "FROM", "GROUP", "HAVING", "IN", "INNER", "IS", "JOIN", "LEADING", "LEFT", "LENGTH", "LIKE", "LOCATE", "LOWER", "MAX", "MEMBER", "MIN", "MOD", "NEW", "NOT", "NULL", "OBJECT", "OF", "OR", "ORDER", "OUTER", "SELECT", "SET", "SIZE", "SOME", "SQRT", "SUBSTRING", "SUM", "TRAILING", "TRIM", "UPDATE", "UPPER", "WHERE", <BOOLEAN_LITERAL>, <DECIMAL_LITERAL>, <IDENTIFIER>, <INTEGER_LITERAL>, <STRING_LITERAL>].
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.parse(JPQLExpressionBuilder.java:1665)
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.<init>(JPQLExpressionBuilder.java:1645)

    The error is indocating improper formatting of your JPQL string. MONTH is not understood. I would recommend using your SQL string in a createNativeQuery(...) call instead.
    Doug

  • @Embeddable with java.uitil.Date in JPQL (limitations ?)

    I'm facing with problem regarding using java.util.Date in JPQL query.
    Here are sample entities for test case:
    @Embeddable
    public class EmbCompTest implements Serializable{
         private static final long serialVersionUID = 1L;
         @Temporal(TemporalType.DATE)
         private Date beginPeriod;
         @Temporal(TemporalType.DATE)
         private Date endPeriod;
                       // getters and setters goes here (...)
    @Entity
    @Table(name="TEST_DATE")
    @NamedQueries(
       @NamedQuery(name="getByDate",query="select e from TestDate e where e.beginDate=:beginDatePm"),
       @NamedQuery(name="getByDate2",query="select e from TestDate e where e.emb.beginPeriod=:beginPeriodPm")
    public class TestDate {
         private static final long serialVersionUID = 6651720114733319974L;
         @Id
         private Long id;
         @Temporal(TemporalType.DATE)
         private Date beginDate;
         @Temporal(TemporalType.DATE)
         private Date endDate;
         @Embedded
         private EmbCompTest emb;
                         // getters and setters goes here (...)
    The problem is in named query getByDate2 which causes persistence unit fail to start with exception
    Caused by: java.lang.IllegalArgumentException: java.lang.IllegalArgumentException: Method must not be called with
    argument "java.util.Date" or "java.util.Calendar"
    Is that some SAP JPA limitation that makes unable to query by date defined in @Embeddable classes ?
    Of course query getByDate works fine.
    Best Regards
    Daniel

    Hi Daniel,
    the query getByDate2 is OK and should work. This looks like a bug to me. If you have access to OSS, please file a ticket on BC-JAS-PER-JPA.
    Have you tried typing beginPeriod with java.sql.Date. This might work. (I have not tried).
    -Adrian

  • Inheritance based on USER column and JPQL based on @ManyToOne column

    I wanted to build a simple inheritence scheme for no other reason than to support a generalized table that I could manipulate in standard libraries and to extend that table with columns that might exist in various customer implementations. In the extra-ordinarily simple example that follows I created a base Parcel class; extend that with a ParcelBean which has a column specific to a user; and extend that further with a wrapper class that will include some Trinidad references that I want to keep completely away from the bean classes. In short, I wanted to put together an inheritence scheme for basic OO reasons, not because of any particular table structure.
    After some thought I figured that the best way to do this might be to use the Single-Table Strategy, especially after I discovered that I could fool the system by using the Oracle USER pseudo-column for my DiscriminatorColumn and use my schema name for the DiscriminatorValue.
    @Entity
    @Table(name = "PARCEL")
    @Inheritance
    @DiscriminatorColumn(name = "USER")
    public class Parcel {
      String parcelPin;
      public Parcel() {
      @Id
      @Column(name = "PARCELPIN", nullable = false)
      public String getParcelPin() {
        return parcelPin;
      public void setParcelPin(String parcelPin) {
        this.parcelPin = parcelPin;
    @Entity
    public class ParcelBean extends Parcel {
      LandUseType luc;
      public ParcelBean() {
      public void setLuc(LandUseType newluc) {
        this.luc = newluc;
      @ManyToOne
      @JoinColumn(name = "LUC")
      public LandUseType getLuc() {
        return luc;
    @Entity
    @DiscriminatorValue("CPC")
    public class ParcelRow extends ParcelBean {
      public ParcelRow() {
      public void doSomething(ActionEvent ae) {
        ; // Trinidad code
    }For a couple of weeks this has been working fine. Right up until I tried to a JPQL like the following:
    "select p from ParcelRow p where p.luc.cpcCode=12"The problem is that TOPLINK will generate SQL that prefixes USER with an alias (something it does not do if there isn't a foreign key reference involved). This won't work because Oracle SQL does not allow aliases on pseudo-columns
    select USER from PARCEL; -- return CPC
    select p.USER from PARCEL p; -- throws ORA-01747: invalid user.table.column specificationSo now I'm in a jam. I can't (read won't if you will) give up on my requirement for inheritence. I have multiple clients with the same basic legacy table with minor variations and I have tens of thousands of lines of code that work on the basic core table properties and I don't want to copy and paste. I could use interfaces, except that I would still have to extend the Beans with my Row classes so that I could add the JSF actionListeners (and other such stuff). I need to be able to select Lists of these Row classes with the JSF methods so that I can expose them as values to JSF/Trinidad/ADF Tables and it break every person pattern I enforce to mix JSF and JPA dependencies in the same class.
    Anyone out there have any ideas?
    Thanks Mark

    Of course a simple fix for this problem would be if the Oracle provider code was smart enough to recognize pseudo columns and to not prefix them with an alias.
    Is there any chance that this might be done before a final release?
    Mark

  • Mapping Problem with Native SQL query

    My application uses a native SQL query to locate certain entities. It looks like this:
    SELECT UPLOADATTEMPTREF, STUDENTNUMBER, USERID, WORKITEMCODE, WORKITEMINSTURN, WORKITEMTITLE, MODULERUNCODE, STUDENTNAME, SUBMISSIONDEADLINE, UPLOADATTEMPTSERVERDATE, FILENAME, UPLOADCOMPLETESERVERDATE, NEWFILENAME, FILESIZE, FILEPATH, DOWNLOADSERVERDATE, MODULECODE, MODULETITLE
    FROM Submission_Attempt WHERE UPLOADATTEMPTREF IN (
    SELECT uploadAttemptRef FROM (" +<br /><br />                         "SELECT MAX(uploadAttemptRef) AS uploadAttemptRef, UserID, workItemInstUrn, " +<br /><br />                         "workItemCode FROM Submission_Attempt where workiteminsturn = ?1 " +<br /><br />                         "GROUP BY UserID, workItemInstUrn, workItemCode) Table1 ) " +<br /><br />                         "and uploadCompleteServerDate is not null;"<br />
    My expectation was that EclipseLink would be able to handle the mapping of the results to the entity quite happily. However, I get a NonSynchronizedVector of Objects - each Object representing one field of data.
    I need help with either:
    Converting the above SQL into JPQL so that I (hopefully) don't have to worry about the SQL or
    Understanding why this isn't working properly...
    Anyone able to help?
    Edited by: phunnimonkey on Nov 6, 2008 3:33 AM

    Never mind - the problem was to do with not specifying a class when creating the native query.

  • Problem in using LIKE expression and mapping relationship: @OTM / @MTO???

    Hi there,
    I have 2 entity classes:
    @Entity
    @Table(name = "DT_KHV_DTL", schema = "DTKB", uniqueConstraints = {})
    public class VoucherDtlEnt {
    bq.      private String id; \\     private DuAnEnt duAnEnt; \\     //... others
    bq.      @Id \\     @Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = false)
    bq. public String getId() {
    bq. bq. return id;
    bq.      } \\     public void setId(String _id) {
    bq. bq. this.id = _id;
    bq. }
    bq.      @ManyToOne(targetEntity = DuAnEnt.class) \\     @JoinColumn(name = "DA_ID")
    bq. public DuAnEnt getDuAnEnt() {
    bq. bq. return this.duAnEnt;
    bq.      } \\     public void setDuAnEnt(DuAnEnt _duAnEnt) {
    bq. bq. this.duAnEnt = _duAnEnt;
    bq. }
    bq. //... others
    @Entity
    @Table(name = "DT_TTDA_C", schema = "DTKB", uniqueConstraints = {})
    public class ProjectEnt {
    bq. private String id; \\ //... others
    bq.      @Id \\     @Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = false)
    bq. public String getId() {
    bq. bq. return id;
    bq.      } \\     public void setId(String _id) {
    bq. bq. this.id = _id;
    bq. } \\ //... others
    bq.
    I want to list details-vouchers which have project id like the search parameter. In SQL this will be: SELECT * FROM DT_KHV_DTL a WHERE a.DA_ID LIKE ?
    I've tried in JPQL with this query:
    bq. SELECT voucherDtlEnt FROM VoucherDtlEnt voucherDtlEnt WHERE voucherDtlEnt.projectEnt.id LIKE :projectId
    Of course it's work but it make a big problem: it will generate a JOIN SQL query like that:
    bq. SELECT t0.id ... FROM DT_KHV_DTL t0, DT_TTDA_C t1 WHERE t0.DA_ID = t1.ID AND t1.ID LIKE ?
    In my real case, the project number is around 10.000, this generation take me from 0.1s in SQL to minutes in JPQL, even in complex situation, it freeze the application server.
    In other case without LIKE, this will be done with:
    bq. SELECT voucherDtlEnt FROM VoucherDtlEnt voucherDtlEnt WHERE voucherDtlEnt.projectEnt = :projectEnt
    which perform a true SQL:
    bq. SELECT t0.id ... FROM DT_KHV_DTL t0 WHERE t0.DA_ID = ?
    So, I've tested:
    bq. SELECT voucherDtlEnt FROM VoucherDtlEnt voucherDtlEnt WHERE voucherDtlEnt.projectEnt LIKE :projectEnt --&gt; Error cause LIKE expression only apply for String type
    bq. SELECT voucherDtlEnt FROM VoucherDtlEnt voucherDtlEnt WHERE voucherDtlEnt.projectEnt LIKE :projectId --&gt; Error cause can't compare 2 dif class: ProjectEnt and String
    Have any solution ???
    +I'd happy if the generator don't check type String in
    the query:+
    bq. SELECT voucherDtlEnt FROM VoucherDtlEnt voucherDtlEnt WHERE voucherDtlEnt.projectEnt LIKE :projectEnt
    instead just check inserted entity have an Id in String type, so can threat this like the '=' expression case.
    bq.

    After review, I've found the problem is not in JOIN but stupid generator do one like this:
    SELECT t0.id ... FROM DT_KHV_DTL t0,{color:#ff0000} DT_KHV_DTL t2{color}, DT_TTDA_C t1 WHERE t0.DA_ID = t1.ID AND t1.ID LIKE ?
    In SQL native query, cause t2 don't identify join column with t0, it will make a big problem that must remove this or just add AND t0.ID = t2.ID
    I'm using Oracle Application Server 10.0.1.3 and have any fixed this in newer versions???
    Still trying to REMOVE

  • 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

  • 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

  • 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

  • Named query in Entity Bean - Problem with embedded class

    Hello Forum,
    I'm trying to set up a named query in my Entity Bean and I'm unable to get
    it up and running for an embedded class object.
    The class hierarchy is as follows:
             @MappedSuperclass
             AbstractSapResultData (contains dayOfAggregation field)
                     ^
                     |
            @MappedSuperclass
            AbstractSapUserData (contains the timeSlice field)
                     ^
                     |
              @Entity
              SapUserDataThe named query is as follows:
    @NamedQuery(name = SapUserDataContext.NAMED_QUERY_NAME_COUNT_QUERY,
                                query = "SELECT COUNT(obj) FROM SapUserData AS obj WHERE "
                                         + "obj.sapCustomerId"
                                         + "= :"
                                         + SapResultDataContext.COLUMN_NAME_SAP_CUSTOMER_ID
                                         + " AND "
                                         + "obj.sapSystemId"
                                         + "= :"
                                         + SapResultDataContext.COLUMN_NAME_SAP_SYSTEM_ID
                                         + " AND "
                                         + "obj.sapServerId"
                                         + "= :"
                                         + SapResultDataContext.COLUMN_NAME_SAP_SERVER_ID
                                         + " AND "
                                         + "obj.dayOfAggregation.calendar"
                                         + "= :"
                                         + DayContext.COLUMN_NAME_DAY_OF_AGGREGATION
                                         + " AND "
                                         + "obj.timeSlice.startTime"
                                         + "= :"
                                         + "timeSliceStartTime"
                                         + " AND "
                                         + "obj.timeSlice.endTime"
                                         + "= :"
                                         + "timeSliceEndTime")The query deploys and runs except that part:
                                         + "obj.dayOfAggregation.calendar"
                                         + "= :"
                                         + DayContext.COLUMN_NAME_DAY_OF_AGGREGATIONI don't see any difference to the part of the query accessing the timeSlice
    field which is also an embedded class object - I access it in exactly the same way:
                                         + "obj.timeSlice.startTime"
                                         + "= :"
                                         + "timeSliceStartTime"
                                         + " AND "
                                         + "obj.timeSlice.endTime"
                                         + "= :"
                                         + "timeSliceEndTime"The problem is that the complete query runs on JBoss application server
    but on the SAP NetWeaver application server it only rund without the
                                         + "obj.dayOfAggregation.calendar"
                                         + "= :"
                                         + DayContext.COLUMN_NAME_DAY_OF_AGGREGATIONpart - If I enable that part on SAP NetWeaver the server complains:
    [EXCEPTION]
    {0}#1#java.lang.IllegalArgumentException: line 1: Comparison '=' not defined for dependent objects
    SELECT COUNT(obj) FROM SapUserData AS obj WHERE obj.sapCustomerId= :sap_customer_id AND obj.sapSystemId= :sap_system_id AND obj.sapServerId= :sap_server_id AND obj.dayOfAggregation.calendar= :day_of_aggregation AND obj.timeSlice.startTime= :timeSliceStartTime AND obj.timeSlice.endTime= :timeSliceEndTime
                                                                                                                                                                                                 ^I know that this isn't an application server specific forum but the SAP NetWeaver server is the most strict EJB 3.0 and JPA 1.0 implementation I've seen so far so I think I'm doing something wrong there.
    Someone in the SAp forum mentioned:
    The problem here is that you compare an input-parameter with an embeddable field of your entity.
    Regarding to the JPQL-grammer (spec 4.14) you are not allowed to compare
    with the non-terminal embeddable field but with the terminal fields of your
    embeddable. Stating that your embedded class might have the fields
    startTime and endTime your JPQL query might look like this:
    Query q = em.createQuery("SELECT count(obj.databaseId) FROM SapUserData obj WHERE obj.timeSlice.startTime = :startTime AND obj.timeSlice.endTime = :endTime");
    q.setParameter("startTime", foo.getStartTime());
    q.setParameter("endTime", foo.getEndTime());
    q.getResultList();
    This limitation in the JPQL grammar is rather uncomfortable.
    An automatic mapping of the parameter's fields to the terminal fields of your
    embedded field would be more convenient. The same can be said for lists
    as parameter-values which is possible in HQL, too. I think we have to wait
    patiently for JPA 2.0 and hope for improvements there. :-)
    With that help I was able to get it up and running for the timeSlice field but
    I don't see the difference to the dayOfAggregation field which is also just
    another embedded class using an object of a class annotated with
    @Embeddable.
    The get method of the dayOfAggregation field is as follows:
         * Get method for the member "<code>dayOfAggregation</code>".
         * @return Returns the dayOfAggregation.
        @Embedded
        @AttributeOverrides({@AttributeOverride(name = "calendar", /* Not possible to use interface constant here - field name must be used for reference */
                                                column = @Column(name = DayContext.COLUMN_NAME_DAY_OF_AGGREGATION,
                                                                 nullable = false)),
                             @AttributeOverride(name = "weekday",
                                                column = @Column(name = DayContext.COLUMN_NAME_WEEKDAY,
                                                                 nullable = false)),
        public Day getDayOfAggregation() {
            return this.dayOfAggregation;
        }The link to my question in the SAP forum for reference:
    https://www.sdn.sap.com/irj/sdn/thread?messageID=3651350
    Any help or ideas would be greatly appreciated.
    Thanks in advance.
    Henning Malzahn

    Hello Forum,
    got a response in the SAP forum - Issue is a bug in the SAP NetWeaver
    app. server.
    Henning Malzahn

  • Need help converting SQL "OVER (PARTITION BY   )" to JPQL equivalent - JPA

    Having trouble converting this query:
    select
    sdi,
    val,
    vldtn,
    TO_CHAR(sdt, 'yyyy-mm-dd hh:mi:ss AM')
    from
    select
    sdi,
    val,
    vldtn,
    sdt,
    max(sdt) over (partition by sdi) as MaxDate1
    from
    r_ins
    ) x
    where x.sdt = x.MaxDate1
    and sdi in (1234,2345,3456,4567,5678,6789,7890);
    to JPQL equivalent using JPA
    Able to convert simple queries but I do not know how to handle the "over (partition by sdi)" portion of the query.
    Can anyone help
    TIA
    Jer

    Paul Horth wrote:
    Why have the power (and cost) of Oracle and then not use those powerful features because you are restricting yourself to a vanilla set of SQL because you are using some generic framework.You know how it is :
    1 - Application developers create code & queries but only test them on tiny database with low volume and no concurrency at all.
    2 - Application goes Live, Database grows (as expected) but stupid optimizer is not as fast as on test environment (that was mostly empty)
    3 - Queries are now 200 times slower.
    4 - Expensive DB expert comes and gathers statistics, creates indexes, rewrites queries, uses hint/outline/SQLprofile.
    Conclusion : Database is evil and prevent application from working efficiently, the proof of all that being : nothing had to be done on application's side to make things work correctly. Database is declared guilty.
    Which could translate to :
    1 - Team buy a formula one with 800HP that can reach 200mph in less than 10 seconds.
    2 - Give it a pilot that doesn't even want to understand what-the-heck is a gearbox/transmission. Pilot only drives in 1st gear.
    3 - The formula one is now doing 0.003 miles per gallon, doing the hell of a noise, and is limited to 80mph +(any $10000 family wagon is faster in average)+
    4 - Expensive expert comes and check everything in the formula one. Finally understand the problem and modify the gearbox to a sloppy automatic transmission
    Conclusion : Formula 1 is evil and prevent pilot from being fast. The proof of that being : nothing had to be changed on pilot's side to make things work correctly. Formula 1 is declared guilty.
    You cannot win race without understanding how the car/engine/transmission/physics/race rules work.
    Too much levels of abstraction is bad. Treating the database as a black box is the most seen "Bad Idea" these days (to my point of view).
    Warning: I am biased towards Oracle :-)And so am I.
    (^_^)

  • Setting new Date() in a JPQL field

    I have written a system where dynamic query is created on-the-fly using a query criteria builder class. Now when a date is passed in.
         * set the value to be used as an equal to search for createDate
         * @param Date - createDate
        public void setCreateDate(Date createDate)
            setParameter(CREATE_DATE, new Date());
        }Now, the problem is the query created is something like
    p.createDate = Fri Dec 21 00:00:00 PST 2007and this stuff throws an IllegalArgumetException while creating the query because of the Fri token.
    My question is how else do I set a date object into JPQL without causing this exception.
    Michael

    I have discovered my first mistake. I was using my criteria class to build a JPQL. using a StringBuffer to concatenate the fields and their values. The problem with dates is that on appending the a toString() is generated for the date object and that String is the cause of the IllegalArgumentException when the query is created.
    So, I am looking for a way get the Date object in place instead of its toString()
    Thanks

Maybe you are looking for