JPA query problem

Hi folks !
I have this class with TemporalType.DATE property
and i want to know if the query i design should look like this:
select a from A a where a.dateProp = :theDateis this sufficient (where theDate should be substituted with a java.util.Date object with only the date,month,year set)?
thanks

Yes. In fact, the problem I've posted is a generalization of a more strange behaviur. The (cutted-off) schema is
Table Charter
id       integer   primary key
company  integer   foreign key (on 'id' of table 'company')
price    decimal
Table Company
id       integer   primary key
name     textNow, assume I have 10 records in table Charter referencing 10 records in table Company (each row in Charter reference a distinct row in Company).
This query returns me THE CORRECT RESULT (that is, each matching row is present in the result set only once):
SELECT o FROM Charter AS o WHERE o.company.id = :company AND 1=1Instead, this query returns me each matching row, BUT REPEATED N TIMES, where N is the number of rows in Charter (10):
SELECT o FROM Charter AS o WHERE 1=1 AND o.company.id = :company(Notice that the only difference is the order of the where clause)
(Notice also that I get the same behaviour even if I do a query on the 'price' field).
Also, this query that should return all the rows in the table (one time each), returns them N times:
SELECT o FROM Charter AS o WHERE 1=1Any idea?
Really thank you
ps I forgot to say that, after translating those JPQL query in standard SQL and executing them in PostgreSQL console, they are, obiouvsly, equivalent and work correctly.
Message was edited by:
Konrad84

Similar Messages

  • How to configure lazy/eager loading for each JPA query

    Hi!
    I have extensive EJB model (entities with many child entities, entities with association to other large (many fields, BLOBs including) entities, and so on) and I would like for each JPA query configure what properties or associated entities (actually - in arbitrary depth) of selected entities should be fetched.
    E.g. for one query I would like to fetch only Order (and no data of associated entities), but for other queries I would like to fetch Order, Order.Customer, Order.ShippingAddress.ZipCode and nothing else ( e.g. if there is Ordere.Route, Order.Billing and other associations, then I would like not to waste resources for fetching them). In both case the select clause of query can include only Order, but the results should be different - i.e. - there is no associated data in the first case and there are some associated data the second case.
    I know that one solution is to declare all associations as lazy and then - after reading the result of query - do some touching for retrieving the associated data:
    String check = order.Customer.toString();
    check = order.ShippingAddess.ZipCode.toString();
    But I see 2 problems with this: 1) it is not nice (resources are wasted for simply touching associated entities); 2) I assume that each "touch" operation generates other query to database that could be executed together with the original query. So - it would be nice to configure JPA query somehow to let it know which associations will be required from the result and which not.
    What is the best practice?
    I found, that JBoss server has lazy-loading-group configuration, but - I guess - it is JBoss specific:
    http://docs.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/4.2/html/Server_Configuration_Guide/Loading_Process-Lazy_loading_Process.html
    besides - it is XML and it would be more pretty if query configuration could be done with annotations!

    JPQL has a "fetch" construct in which you can force a lazy element to be fetched using a query - I must note that I have had unexpected results with it in the past but that was using an old version of Hibernate and I wasn't very experienced with JPA yet.
    http://docs.oracle.com/cd/E15051_01/wls/docs103/kodo/full/html/ejb3_langref.html#ejb3_langref_fetch_joins

  • Convert JPA Query getResultList to Array

    I have been struggling with this problem for several hours now. All I have succeeded in doing is attempt every possible way to convert a List into an array and I just get errors.
         // create native SQL query
         Query q = em.createNativeQuery("SELECT * FROM Project p");
         // get and process the results
         List<Project> list = q.getResultList();
            Project[] retVal = new Project[list.size()];
         for (int i = 0; i < list.size(); i++)
             retVal[i] = list.get(i);
         }One would assume this to work, however this generates a ClassCastException, cannot convert Object to Project, oddly because as far as I can see everything in the code is strongly typed. I think Persistence fills the typed List with Object and not Project??
    So I tried:
    Project[] retVal = list.toArray(new Project[0]);This generates an ArrayStoreException.
    Finally I tried the basic, should generate x-lint warning:
    Project[] retVal = (Project[])(list.toArray());This also return ClassCastException, same reason as the first attempt.
    I want my WebService function to return a standard Project[] not the java.lang.List class. But it seems JPA queries only support getting a List. I have googled to no end for a solution. Help appreciated!
    Thanks.

    You are almost right, you can solve this two ways as below:
    First, use native query with result class reference.
    Second, use JPA query with createQuery method.
    Both the options should work, see code below:
    // First option, create native SQL query with result class reference.
    Query q = em.createNativeQuery("SELECT * FROM Project p",Project.class);
    // Second option, Create JPA Query.
    // Query q = em.createQuery("SELECT p FROM Project p");
    // get and process the results
    List<Project> list = q.getResultList();
    // Putting result to an array
    Project[] retVal = new Project[list.size()];
    list.toArray(retVal);*Cheers,
    typurohit* (Tejas Purohit)

  • General JPA query question

    Hello world,
    I'm new to JPA 2.0 and there are few things I don't understand.
    BTW: I can't figure out the keywords to search for this question, so please pardon me if it's one of the most asked.
    Using the Preview, I've seen that alignment went straight to Hell, so I tried to make this as readable as I could using pipes in place of white spaces in the result sets.
    I have a couple of tables:
    CUST table (for customers):
    CUST_ID (pk, integer)
    CUST_NAME (varchar)
    ORD table (for orders):
    ORD_ID (pk, integer)
    ORD_STATUS (char) can be: N for new, S for shipped, D for delivered
    CUST_ID (fk, integer)
    The relationship is, of course, a "one to many" (every customer can place many orders).
    Content of the tables:
    CUST_ID|CUST_NAME
    1|elcaro
    2|tfosorcim
    3|elppa
    ORD_ID|ORD_STATUS|CUST_ID
    2|N|1
    3|N|1
    4|N|1
    5|S|1
    6|S|1
    7|D|1
    8|D|1
    9|D|1
    10|D|2
    11|N|2
    12|S|3
    13|S|3
    Here's how I annotated my classes:
    Customer.java:
    @Entity(name = "Customer")
    @Table(name = "CUST")
    public class Customer implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "CUST_ID")
    private Integer id;
    @Column(name = "CUST_NAME")
    private String name;
    @OneToMany(mappedBy = "customer")
    private List<Order> orders;
    // Default constructor, getters and setters (no annotations on these)
    Order.java:
    @Entity(name = "Order")
    @Table(name = "ORD")
    public class Order implements Serializable
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "ORD_ID")
    private Integer id;
    @Column(name = "ORD_STATUS")
    private Character status;
    @ManyToOne
    @JoinColumns
    @JoinColumn(name = "CUST_ID", referencedColumnName = "CUST_ID")
    private Customer customer;
    // Default constructor, getters and setters (no annotations on these)
    Everything works just fine, the following JPQL query yields the results I expected:
    select c from Customer c
    it returns three objects of type Customer, each of which contains the orders that belong to that customer.
    But now, I want to extract the list of customers that have orders in status 'N', along with the associated orders (only the status 'N' orders, of course).
    Back in the good ol' days I would have written an SQL query like this:
    select c.cust_id, c.cust_name, o.ord_id, o.ord_status
    from cust c
    inner join ord o on (o.cust_id = c.cust_id)
    where o.ord_status = 'N'
    and it would have returned the following result set:
    CUST_ID|CUST_NAME|ORD_ID|ORD_STATUS
    1|elcaro|2|N
    1|elcaro|3|N
    1|elcaro|4|N
    2|tfosorcim|11|N
    The following JPQL query, however, doesn't yield the expected results:
    select distinct c from Customer c join c.orders o where o.status = 'N'
    it returns the correct set of customers (customer 'elppa' doesn't have any status 'N' order and is correctly excluded), but each customer contains the full set of orders, regardless of the status.
    It seems that the 'where' clause is only evaluated to determine which set of customers has to be extracted and then the persistence provider starts to navigate the relationship to extract the full set of orders.
    Thinking a little about it, I must admit that it makes sense.
    I then tried out another JPQL query:
    select c, o from Customer c join c.orders o where o.status = 'N'
    this JPA query yields results that are similar to the ones produced by the previous SQL query: each result (4 results as expected) is a 2-object array, the first object is of type Customer and the second object is of type Order. But, again, the objects of type Customer contain the full set of related orders (as I expected, this time). Not to mention the fact that now the orders are not contained in the Customer objects, but are returned separately, just as in an SQL result set.
    Now the question is:
    Is it possible to write a JPA query that filters out, not only the customers that don't have an order in status 'N', but the related orders (fetched during relationship navigation) that are not in status 'N' as well?
    What I'd like to be able to get is a 2-customer result where each customer contains only its status 'N' orders.
    I read the Java EE 6 Tutorial and one of the examples (the Order Application) has a schema that is similar to mine, but I couldn't find a query like this (in the downloaded source code).
    Although I think the above is standard behavior, I use an Oracle Weblogic 12c server (through its Eclipse adapter) and the persistence provider appears to be EclipseLink.
    Thanks in advance.
    Best regards,
    Stefano
    Edited by: user11265230 on 17-apr-2012 14.11

    Hello,
    When returning an entity from JPQL, it gives you the entity as it is in the database. Your "select distinct c from Customer c join c.orders o where o.status = 'N'" is asking for all customers that have an order with a status of 'N', so that is what it gives you. There is no condition to filter anything on the relationship when building the Customer object in JPA - doing so would mean returning a managed entity that does not reflect what is in the database. This would affect other queries, since JPA requires that queries return the same instance of an entity regardless of the query that is used to bring it back. So a query using your "where o.status = 'N'" would cause conflicting results when used with a query using "where o.status = 'Y'". And these queries would make the EntityManager unable to determine what has changed on the returned objects.
    EclipseLink does have the ability to filter over relationships, it is just not available through standard JPA and I would strongly discourage it. Instead of querying for Customers, why not change the query to get Orders instead -
    "select o from Customer c join c.orders o where o.status = 'N'". Assuming Orders have a ManyToOne back reference to their Customer, this will mean you do not need to travers the Customer-> order relationship. If using
    "select c, o from Customer c join c.orders o where o.status = 'N'"
    I am not sure why you would use the orders from the returned customers instead of the orders returned in the results though.
    You could also return "select c.id, c.name, o.id, o.status from Customer c join c.orders o where o.status = 'N'" which is the equivalent of what you would get from the SQL you initially posted.
    Regards,
    Chris

  • Designing LOV Query Problem

    Hello APEX people,
    I posted my problem here:
    Designing LOV Query Problem
    What I have is a sequence like this:
    CREATE SEQUENCE
    DR_SEQ_FIRST_SCHEDULE_GROUP
    MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
    CACHE 6 ORDER CYCLE ;
    What I need would be a SQL query returning all possible values oft my sequence like:
    1
    2
    3
    4
    5
    6
    7
    I want to use it as a source for a LOV...
    The reason why I use the cycling sequence is: My app uses it to cycle scheduling priorities every month to groups identified by this number (1-7).
    In the Admin Form, I want to restrict the assignment in a user friendly way - a LOV.
    Thanks
    Johann

    Here ist the solution (posted by michales in the PL/SQL forum):
    SQL> CREATE SEQUENCE
    dr_seq_first_schedule_group
    MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
    CACHE 6 ORDER CYCLE
    Sequence created.
    SQL> SELECT LEVEL sn
    FROM DUAL
    CONNECT BY LEVEL <= (SELECT max_value
    FROM user_sequences
    WHERE sequence_name = 'DR_SEQ_FIRST_SCHEDULE_GROUP')
    SN
    1
    2
    3
    4
    5
    6
    7
    7 rows selected.

  • SQL+-MULTI TABLE QUERY PROBLEM

    HAI ALL,
    ANY SUGGESTION PLEASE?
    SUB: SQL+-MULTI TABLE QUERY PROBLEM
    SQL+ QUERY GIVEN:
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE FROM PATIENTS_MASTER1, HAEMATOLOGY1,
    DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM AND PATIENT_NUM = DLC_PATIENT_NUM AND PATIENT_NUM
    = &PATIENT_NUM;
    RESULT GOT:
    &PATIENT_NUM =1
    no rows selected
    &PATIENT_NUM=2
    no rows selected
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    ACTUAL WILL BE:
    &PATIENT_NUM=1
    PATIENT_NUM 1
    PATIENT_NAME BBBB
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 5
    HMTLY_RBC_NORMAL 4.6-6.0
    &PATIENT_NUM=2
    PATIENT_NUM 2
    PATIENT_NAME GGGG
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     42
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    4 TABLES FOR CLINICAL LAB FOR INPUT DATA AND GET REPORT ONLY FOR TESTS MADE FOR PARTICULAR
    PATIENT.
    TABLE1:PATIENTS_MASTER1
    COLUMNS:PATIENT_NUM, PATIENT_NAME,
    VALUES:
    PATIENT_NUM
    1
    2
    3
    4
    PATIENT_NAME
    BBBB
    GGGG
    KKKK
    PPPP
    TABLE2:TESTS_MASTER1
    COLUMNS:TEST_NUM, TEST_NAME
    VALUES:
    TEST_NUM
    1
    2
    TEST_NAME
    HAEMATOLOGY
    DIFFERENTIAL LEUCOCYTE COUNT
    TABLE3:HAEMATOLOGY1
    COLUMNS:
    HMTLY_NUM,HMTLY_PATIENT_NUM,HMTLY_TEST_NAME,HMTLY_RBC_VALUE,HMTLY_RBC_NORMAL_VALUE     
    VALUES:
    HMTLY_NUM
    1
    2
    HMTLY_PATIENT_NUM
    1
    3
    MTLY_TEST_NAME
    HAEMATOLOGY
    HAEMATOLOGY
    HMTLY_RBC_VALUE
    5
    4
    HMTLY_RBC_NORMAL_VALUE
    4.6-6.0
    4.6-6.0
    TABLE4:DIFFERENTIAL_LEUCOCYTE_COUNT1
    COLUMNS:DLC_NUM,DLC_PATIENT_NUM,DLC_TEST_NAME,DLC_POLYMORPHS_VALUE,DLC_POLYMORPHS_
    NORMAL_VALUE,
    VALUES:
    DLC_NUM
    1
    2
    DLC_PATIENT_NUM
    2
    3
    DLC_TEST_NAME
    DIFFERENTIAL LEUCOCYTE COUNT
    DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE
    42
    60
    DLC_POLYMORPHS_NORMAL_VALUE
    40-65
    40-65
    THANKS
    RCS
    E-MAIL:[email protected]
    --------

    I think you want an OUTER JOIN
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE
    FROM PATIENTS_MASTER1, HAEMATOLOGY1,  DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM (+)
    AND PATIENT_NUM = DLC_PATIENT_NUM (+)
    AND PATIENT_NUM = &PATIENT_NUM;Edited by: shoblock on Nov 5, 2008 12:17 PM
    outer join marks became stupid emoticons or something. attempting to fix

  • JPA query language syntax

    My question is if JPA query language syntax allows full qualified class names in the SELECT clause of the query, e.g.:
    SELECT * FROM com.abc.Person
    This works well with Hibernate, but TopLink Essentials complains about the dots in com.abc.Person.
    In the Java EE 5 Tutorial only partially qualified names ( SELECT * FROM Person) are used.
    There are only examples with fully qualified names for constants in WHERE clauses.

    my first guess:
    SELECT t FROM tablename t WHERE t.timestamp>:somethingwhere :something
    is handled with something like: (..).setParameter("something", someSQLDate);

  • JPA Query set parameter list of objects

    Hi Experts,
    Currently i am looking for the resolution to the the following JPA Query. I am sure you guys already came across the answer for that. Please help me to spot some light.
    Assume a relation Employees --> Departments. I have list of department and i would like to get all the employees belong to the departments. I was trying using the following JPA query
    Select o from EmployeeEntity where o.deparment IN ( :departments ) then set the parameter value to the List of department objects. Now i am getting the following exception
    at org.eclipse.persistence.exceptions.QueryException.invalidOperatorForObjectComparison(QueryException.java:598)
         at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:388)
         at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:218)
    Any hit ?
    Thanks

    Hi,
    You can try the following query
    select e from Employees e where e.Departments.departmentid in (:deptno)
    then set the parameter value to the List of departmentid
    Thanks

  • EJBQL query problem in JPA

    I am developing an Enterprise application that uses JPA and toplink as the persistence provider. It uses MYSQL 5.1.
    The query used in the Entity class is :
    @NamedQueries({@NamedQuery(name = "AirtravelsDynamic.findAllEconomyFlights", query = "select NEW com.inter.transfer.Response(rf.flightno,d.economyseats,rf.ecofare,rf.arrtime,rf.depttime) from AirtravelsDynamic d LEFT JOIN d.refId rf where rf.source=?1 and rf.destination=?2 and d.availdate between ?3 and ?4") })
    This application is giving the following exception:
    Exception Description: Error compiling the query [AirtravelsDynamic.findAllEconomyFlights: select NEW com.inter.transfer.Response(rf.flightno,d.economyseats,rf.ecofare,rf.arrtime,rf.depttime) from AirtravelsDynamic d LEFT JOIN d.refId rf where rf.source=?1 and rf.destination=?2 and d.availdate between ?3 and ?4], line 1, column 40: invalid navigation expression [rf.flightno], cannot navigate expression [rf] of type [int] inside a query.
    Local Exception Stack:
    Exception [TOPLINK-8029] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EJBQLException
    Exception Description: Error compiling the query [AirtravelsDynamic.findAllEconomyFlights: select NEW com.inter.transfer.Response(rf.flightno,d.economyseats,rf.ecofare,rf.arrtime,rf.depttime) from AirtravelsDynamic d LEFT JOIN d.refId rf where rf.source=?1 and rf.destination=?2 and d.availdate between ?3 and ?4], line 1, column 40: invalid navigation expression [rf.flightno], cannot navigate expression [rf] of type [int] inside a query.
    at oracle.toplink.essentials.exceptions.EJBQLException.invalidNavigation(EJBQLException.java:430)
    at oracle.toplink.essentials.internal.parsing.DotNode.checkNavigation(DotNode.java:141)
    at oracle.toplink.essentials.internal.parsing.DotNode.validate(DotNode.java:97)
    at oracle.toplink.essentials.internal.parsing.ConstructorNode.validate(ConstructorNode.java:97)
    at oracle.toplink.essentials.internal.parsing.SelectNode.validate(SelectNode.java:329)
    at oracle.toplink.essentials.internal.parsing.ParseTree.validate(ParseTree.java:229)
    at oracle.toplink.essentials.internal.parsing.ParseTree.validate(ParseTree.java:211)
    at oracle.toplink.essentials.internal.parsing.ParseTree.validate(ParseTree.java:201)
    at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.populateReadQueryInternal(EJBQLParseTree.java:134)
    at oracle.toplink.essentials.internal.parsing.EJBQLParseTree.populateQuery(EJBQLParseTree.java:108)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:219)
    at oracle.toplink.essentials.queryframework.EJBQLPlaceHolderQuery.processEjbQLQuery(EJBQLPlaceHolderQuery.java:111)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.processEJBQLQueries(AbstractSession.java:2059)
    at oracle.toplink.essentials.internal.sessions.AbstractSession.processEJBQLQueries(AbstractSession.java:2046)
    at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:724)
    at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:604)
    at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:280)
    at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:229)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:93)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:126)
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:120)
    at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:91)
    Any help is appreciated.
    Thanks in advance.

    What are you trying to do exactly? The way you've used LEFT JOIN is not correct if d.refId is an integer. LEFT JOIN is used to retrieve a set of entities where that set may not exist. It doesn't look like refId is a set of anything, just an integer.
    It looks like maybe you intended to have a foreign key relationship between AirtravelsDynamic and some other entity. In that case you probably want to model your AirtravelsDynamic entity as having a many-to-one relationship with the entity (let's call it ref.)
    The relationship would look something like:
    @Entity
    public class AirtravelsDynamic
       @ManyToOne
       @JoinColumn(name="refId")
       private Ref ref;
    }Then your query would read:
    SELECT new com.inter.transfer.Response(d.ref.flightno, d.economyseats,
                                           d.ref.ecofare, d.ref.arrtime,
                                           d.ref.depttime)
      FROM AirtravelsDynamic d
    WHERE d.ref.source = :refSource
       AND d.ref.destination = :refDest
       AND d.availDate between :lowDate and :highDateIf I'm misunderstanding your intent, let me know and I'll try to help you resolve the problem.

  • JPA query by entity/object ?

    I am trying to write an abstract API which dynamically assigns any Entity Class that needs to be persisted and retrieved using the Entity Manager.
    Saving into the database is not a problem, I just do entityManager.save(Class) and it works for any class that needs to be persisted.
    However, when querying for the object based upon the attributes, I want to avoid naming particular attributes and want to use the Entity class's attributes against itself for querying.
    For example, the client program will say something like this to query by name and age of a Person:
    -------calling (client) program: ---
    Person p = << get from UI, not saved yet, no Id but has all other attributes like name and age etc. >>
    List<Person> persons = dao.getAllThatMatch(p);
    --- end client Program --
    --- DAO class ---
    List<T> getAllThatMatch(T t) {  //note that expectation is that returned is a list of Object which is the same as the querying object
    List<T> entityList = em.someFinderMethod(t);
    //the someFinderMethod method should automatically query for all Person objects that match the attributes provided by the object of Person supplied as criteria
    //NOTE: there is no attribute mentioned extensively like name, age etc.
    return entityList ;
    -- end DAO class --
    Edited by: user7626479 on Feb 6, 2013 3:55 PM
    Edited by: user7626479 on Feb 6, 2013 3:55 PM

    Query by example is not included in the JPA standard, but it is possible to do with EclipseLink.
    See http://wiki.eclipse.org/EclipseLink/Examples/JPA/ORMQueries#Query_By_Example
    for how to use query by example with native EclipseLink queries. To execute a native query through JPA, you will need to call createQuery(DatabaseQuery query) on the org.eclipse.persistence.jpa;JpaEntityManager obtained from the javax.persistence.EntityManager instance by calling getDelegate() or unwrap.
    Best Regards,
    Chris

  • TopLink JPA join problems.

    I need a bit of help here, I hope someone can give me a few pointers...
    I've been building out an Object Relational mapping in TopLink using the bean-style interfaces. On one of my objects I have a 1:M relationship to another table, so
    One Key in T1 -> >1 Keys in T2.
    Pretty simple really. I'm doing it like this:
    @JoinTable( name=, etc. etc.)
    private Set<ObjectForTable2> variableName.
    When I call the getVariableName() method, I get back an IndirectSet (as a set) from the method as expected; however, the size of this set is either 0 or 1.
    In Table 2 I have approximately a dozen rows which correspond to the join key, and when I run the query toplink is building in my SQL shell, I get back the dozen rows. When TopLink does it, I only get to see the first row. Is there some other trick I need to use with the set returned? Right now when I call mySet.size() on the Set returned from getVariableName() I get a size of 1 or 0. (I only get 0 if I change the key to one that does not exist in table 2.)
    if I use the iterator method, such as
    for ( final Iterator i = mySet.iterator(); i.hasNext(); ) {
    ObjectForTable2 myObj = (ObjectForTable2)i.next();
    System.out.println( myObj.getXXX() );
    I still only get one result out. Help! What am I doing wrong here? Do I need to configure something to pull back more than one record from the database?
    Also, how does one use the Oracle bugtracker for this open-source product, if I don't have a service contract?
    Thanks,
    Robbie

    Exactly.
    In TopLink (and in JPA in general) you need identify the field, or combination of fields that are used to uniquely identify entities. As Doug mentioned, it is most common that these fields are the PK of the database.
    Based on your response above I assume that you had a non unique field mapped as the PK of the enitity. This could cause the trouble you are experiencing. Mapping the pk to a unique field (or combination of fields) will likely solve this problem.

  • Reg: Query Problem for New Posting Period

    Hi Xperts,
    While I try to Map the A/P Invoices with their respective Outgoing Payment,
    I used the following Query and it's Query Printlayout
    SELECT T0.DocNum [Payment#], T0.DocDate [Payment Date],
    T0.CardCode, T0.CardName, T1.InvoiceId, T2.DocNum [AP Inv#],
    T2.NumatCard [Bill No.], T2.DocDate [Bill Date], T1.selfInv,
    T1.SumApplied, T1.WtAppld, T0.NoDocsum 
    FROM  [dbo].[OVPM] T0  INNER  JOIN
    [dbo].[VPM2] T1  ON  T1.[DocNum] = T0.DocNum
    INNER  JOIN [dbo].[OPCH] T2  ON  T2.[DocEntry] = T1.DocEntry
    WHERE T0.Cardname='[%0]' and T0.DocDate='[%1]' and
    T0.DocNum='[%2]'
    I got the above query from our Expert Mr.Sambath only.
    Now what is the problem is the query is retrieving the payment details of old Posting Period only and not the current posting period.
    In detail, I used 'Primary' Series for FY08-09, Period indicator 'Default'
    Now I'm using 'Primary1' Series for FY09-10, Period indicator '0910'
    Thanx in adv.
    Regards,
    Bala

    Hi Bala,
    Looking at your query, it is not query issue ,it is your data issue.
    Please check if you have data in  VPM2  table  which is bank transfer payment method
    Thank you
    Bishal
    Edited by: Bishal Adhikari on Apr 9, 2009 8:48 AM

  • VIEW Query Problem

    Hi Greg,
    I had created a view on a table which doesn't have Primary Key, but it has Unique and Not Null constraints on required columns.
    I had wrote a procedure to query the data on VIEW. I have experienced strange problem, very first call to procedure will take more time than succeeding requests. For example from second request onwards, it returns data in < 2 Sec, but first transaction is taking 12 Sec to 30 Sec.
    I thought that very first time VIEW is taking time to refresh it self. So, I added FORCE keyword in CREATE VIEW stattement. However, that doesn't helped out.
    In my further investigation I came to know that base table on which VIEW created, has to be loaded in to memory before querying on VIEW.
    So, I had executed a simple select statement on base table, before I execute VIEW query in procedure.
    With this change I got results consistently < 2 Sec all the times.
    My question is instead of executing the select statement on base table is there a way to load base tables data in memory before querying on VIEW?
    Thanks,
    Subbarao

    Hi,
    A view is nothing but parsed SQL statements stored in the database, a view may or may not run faster. If you execute the SQL used to define the view how much time is it taking. If you want try looking at MATERIALIZED VIEW , that may help you.
    thanks

  • Date range query  problem  in report

    Hi all,
    I have created a report based on query and i want to put date range selection but query giving problem.
    If i am creating select list selection then it is working fine means it will display all records on the particular date.
    But what i need is that user will enter date range as creation_date1,creation_date2 and query should return all the records between these date range. i want to pass it by creating items, i created two items and passing creation_date range to display all records but not displaying and if not passing date then should take null as default and display all records
    Here is the query:
    /* Formatted on 2006/12/10 20:01 (Formatter Plus v4.8.0) */
    SELECT tsh."SR_HEADER_ID", tsh."SALES_DEPT_NUMBER", tsh."COUNTRY",
    tsh."LOCAL_REPORT_NUMBER", tsh."ISSUE_DATE", tsh."SUBJECT",
    tsh."MACHINE_SERIAL_NUMBER", tsh."MACHINE_TYPE", tsh."MACHINE_HOURS",
    tsh."STATUS"
    FROM "TRX_SR_HEADERS" tsh, "TRX_SR_PARTS" tsp
    WHERE (tsh.status LIKE :p23_status_sp OR tsh.status IS NULL)
    AND (tsh.machine_type LIKE :p23_machine_type_sp)
    AND ( tsh.machine_serial_number LIKE
    TO_CHAR (:p23_machine_serial_number_sp)
    OR tsh.machine_serial_number IS NULL
    AND ( TO_CHAR (tsh.failure_date, 'DD-MON-YY') LIKE
    TO_CHAR (:p23_failure_date_sp)
    OR TO_CHAR (tsh.failure_date, 'DD-MON-YY') IS NULL
    AND ( TO_CHAR (tsh.creation_date, 'DD-MON-YY')
    BETWEEN TO_CHAR (:p23_creation_date_sp)
    AND TO_CHAR (:p23_creation_date_sp1)
    OR TO_CHAR (tsh.creation_date, 'DD-MON-YY') IS NULL
    AND (tsh.issue_date LIKE :p23_date_of_issue_sp OR tsh.issue_date IS NULL)
    AND (tsh.country LIKE :p23_country_sp OR tsh.country IS NULL)
    AND ( tsh.local_report_number LIKE TO_CHAR (:p23_local_rep_num_sp)
    OR tsh.local_report_number IS NULL
    AND ( tsp.part_number LIKE TO_CHAR (:p23_part_number_sp)
    OR tsp.part_number IS NULL
    AND tsh.machine_type IN (
    SELECT DISTINCT machine_type
    FROM trx_sales_dept_machine_list
    WHERE sales_department_id IN (
    SELECT DISTINCT sales_department_id
    FROM trx_user_sales_department
    WHERE UPPER (user_name) =
    UPPER ('&APP_USER.'))
    AND SYSDATE >= valid_from)
    AND tsh.sr_header_id = tsp.sr_header_id
    can any one tell me wat is wroung in this query.
    Any other way to write this?
    Thank You,
    Amit

    Hi User....
    Here is some date range SQL that my teams uses with some success:
    For date columns that do not contain NULL values, try this (note the TRUNC, it might help with your "today" problem).
    The hard coded dates allow users to leave the FROM and TO dates blank and still get sensible results (ie a blank TO date field asks for all dates in the future.
    AND TRUNC(DATE_IN_DATABASE)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),:
    :P1_DATE_TO)
    For date columns that contain NULL values, try this (a little bit trickier):
    AND nvl(TRUNC(DATE_IN_DATABASE),
    decode( :P1_DATE_FROM,
    decode( :P1_DATE_TO,
    TO_DATE('30-DEC-3000'),
    NULL),
    NULL)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),
    :P1_DATE_TO)
    Note the 30-DEC-3000 versus 31-DEC-3000. This trick returns the NULL dates when the FROM and TO date range items are both blank.
    I hope this helps.
    By the way, does anyone have a better way of doing this? The requirement is given a date column in a database and a FROM and a TO date item on a page,
    find all of the dates in the database between the FROM and TO dates. If the FROM date is blank, assume the user want all dates in the past (excluding NULL dates). If the TO date is blank, assume that the user wants all of the dates in the future (excluding NULL dates). If both FROM and TO dates are blank, return all of the dates in the databse (including NULL dates).
    Cheers,
    Patrick

  • Multiprovider Query Problem

    Hi Gurus,
    The scenario is that there are 2 inficubes, one with order data and other with delivery data. The cube with order data has the requested delivery date and the delivery cube has the actual delivery date. The problem is that I have a query on a multiprovider (on top of the 2 cubes). So when I output the query data by the sales order number, the result is fine, but when I drill down on any of the dates mentioned above ( they are free characteristics in the query), the result splits up into 2 records. For Eg.
    Sales Order     Req Del Date  Act Del Date  Order Qty  Shipped Qty
    12345               03/03/08         -                    5                 -
                                   -           06/03/08            -                5
    What can I do to get the result in one row?
    I will reward points for any help.
    Thanks

    This is the behavior of the multiprovider, since the actual goods issue date is not part of the orders cube, then it will create a second record. There are a couple solutions you could get around to this:
    1. You could merge the data in one DSO before you actually load it to the data target. To do this, you could update fields you need to the orders ods from the delivery ods.
    2. You could create an infoset between the two cubes if you are in 7.0, otherwise, you could create infoset using the underlying ods and create a query from the infoset: performance wise this is not recommended.
    3. If you want to solve the issue report level, there is what is called constant selection and you can make the actual goods issue date as a constant selection and you can get one line.
    /people/prakash.darji/blog/2006/09/19/the-hidden-secret-of-constant-selection
    I would recommend the last option,
    thanks.
    Wond

Maybe you are looking for