JPA query

Hi:
I am studying JPA with Toplink in Netbeans 6.0
I followed the tutorial for this and it created a users table with an autoincrement primary key as an Id.
Everything is nice.
My question is:
If I have a very large table and I would like to retrieve all the records in that table equal to a field that is not the ID,
how does JPA handle this, does it build a new index for this field or do I have to add it before hand?
What do I have to do in order to make it more efficient?
Is there an example that you could refer me to?
Thanks for your time.

I doubt JPA will create the index for you automagically, it wouldn't know how to.
There may (I don't have my JPA book with me) be an annotation that tells JPA that there should be an index on a field, but if there isn't you'd have to create that yourself.

Similar Messages

  • 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

  • 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

  • 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

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

  • 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

  • What to be targetted by JPA query?

    In JPA the SELECT query is against entity objects, but the UPDATE against DB records, aren't they?
    i coded some basic JPA staff, then found that the getResultList() method to SELECT query always returned the latest states of entity objects but not of DB records, in contrast the executeUpdate() method to UPDATE query always changed the values of DB records but not of entity objects.
    Unfortunately i couldn't prove it from JPA Spec directly. What are the reasons behind? Pls correct me if i were wrong. Thx!
    Edited by: solfan on Jun 24, 2009 3:26 AM

    I suggest you first study and understand fully what the relation between a "transaction", an "entity manager" and a "managed entity" is, before you make any further assumptions.

  • JPA Query.setFirstResult(int) ... What if the table has much more entries

    Hello.
    I want to page my query results but I have a table that has a long primary key. As I see Querry.setFirstResult() can only take an int as a parameter.
    How can I page my results if I have much more than 2,147,483,647 entries? I could implement it by myself... but isn't there some standard way?

    gimbal2 wrote:
    I'd say in theory it is not possible to do that with JPA (or the underlying ORM implementations). Luckily in practice there is no need for such functionality. Who is going to paginate more than 2 billion results?I find it very plausible. Say you have a table that might grow very large ... with A LOT of entries ( more than 2 bilion ) and you want to be able to browse all of them in a client GUI.

  • Coherence+JPA query issues

    Hello everyone,
    I've setup Coherence 3.6 to use JPA according to the generic instructions found here [http://coherence.oracle.com/display/COH35UG/Configuring+Coherence+for+JPA]
    This works fine and I can actually get data out of the DB backed cache. What I've found however is that CohSQL queries do not return anything unless the entry is already in Coherence. I'm using this piece of code to test query Coherence
    public <T> List<T> getAll(Class<T> type) {
            final List<T> data = new ArrayList<T>();
            Filter filter = QueryHelper.createFilter("value().class=?1", new Object[] { type });
            Set<Map.Entry<?, T>> filteredSet = cache.entrySet(filter);
            for (Map.Entry<?, T> t : filteredSet) {
                data.add(t.getValue());
            return Collections.unmodifiableList(data);
      }Should I be expecting Coherence to query the DB at this point, or is CohSQL confined to whatever's already in the cache?
    Thanks
    Edited by: 876420 on 01-Aug-2011 07:07

    Section 20 of the dev guide:
    "It should be noted that queries apply only to currently cached data (and will not use the CacheLoader interface to retrieve additional data that may satisfy the query). Thus, the data set should be loaded entirely into cache before queries are performed. In cases where the data set is too large to fit into available memory, it may be possible to restrict the cache contents along a specific dimension (for example, "date") and manually switch between cache queries and database queries based on the structure of the query. For maintainability, this is usually best implemented inside a cache-aware data access object (DAO)."
    Cheers,
    Steve

  • Jpa query with parameters in Greek

    Hello
    I use netbeans 6.9.1 and toplinlk essensials for jpa connected to a mysql database
    mysql database constants:
    character_set_database = utf8
    character_set_server = utf8
    character_set_system = utf8
    I have this code
    Query qItemom = emOpsw.createQuery("SELECT m FROM Itemom m WHERE "
    + " m.book = :book AND m.omfile = :omfile AND m.omaster = :omaster ");
    qItemom.setParameter("book", (short)1);
    qItemom.setParameter("omfile", (byte)2);
    qItemom.setParameter("omaster", "ΕΚΡ");
    The "omaster" parameter is a String. When i pass latin characters i get results, but when i pass
    a greek character string "ΕΚΡ" for example, i do not get any results at all.
    Can anyone help me?
    Than you in advance.

    Could be a MySQL or JDBC issue. Try the same query using raw JDBC and the bind parameter.
    You could also try disabling parameter binding, if the issue has to do with your JDBC driver's binding.
    James : htttp://www.eclipselink.org

  • How to view SAP JPA query

    Hi All,
    In Hibernate we can see the query by setting in persistence xml file
    <property name="show_sql">true</property>
    Do we have anything like this in SAP JPA so that i can see the actual query ?
    If not is there any place in Server where can I check the fired query?
    Many Thanks

    Hi Arvind,
    You can monitor JPA Cache, for more details please have look of the below help
    Using JPA Monitors - Monitoring - SAP Library
    Thanks,
    Hamendra

  • "select new" in jpa query: does this feature support setters ?

    I use JPA queries and a want to use this syntax:
    view plaincopy to clipboardprint?
    select new pack.UserDto(u.id, u.name) from User  select new pack.UserDto(u.id, u.name) from User
    But I'd like to use setters instead of constructor here.
    Is it possible ?

    I use JPA queries and a want to use this syntax:
    view plaincopy to clipboardprint?
    select new pack.UserDto(u.id, u.name) from User  select new pack.UserDto(u.id, u.name) from User
    But I'd like to use setters instead of constructor here.
    Is it possible ?

  • Syntax of jpa query

    Query query = em.createQuery("select of from employees o where o.status : = status and o.lastName LIKE 'lastName%'");
    query.setParameter("status", "A");
    query.setParameter("lastName","Anne");
    when i try to run the program with this code, I get the following error:
    Caused by: java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational operator
    Edited by: user597294 on Sep 20, 2011 8:19 AM

    Query query = em.createQuery("select o from employees o where o.status = :status and o.lastName LIKE :lastName");
    query.setParameter("status", "A");
    query.setParameter("lastName","Anne%");

  • Jpa query fail! :(

    Hello! I have a simple problem (I think and hope!), I have the next query with subquery:
    select pfs from Person pfs where ...... and pfs NOT IN (select dae.socisPersons.person from DadesAnualsEntitat dae where ......)
    DadesAnualsEntitat have a Set<PersonaFisicaSoci> named "socisPersons" and PersonaFisicaSoci has a Person named "person".
    I don't know how to do because the correct would be 'NOT IN (select dae.socisPersones from DadesAnualsEntitat dae where...)' but they're incompatible objects. There are too much navigations, I know. Some idea? sorry for my poor english, thanks a lot!

    Try comparing on the Id instead of the object,
    i.e.
    pfs.id not in (select dae.socisPersons.person.id from...
    James : http://www.eclipselink.org

Maybe you are looking for