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.
Similar Messages
-
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.11Hello,
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 -
What is the best way to query planned orders or work orders for make items and identify the buy component that is short for supply and vice versa?
What is the best way to query planned orders or work orders for make items and identify the buy component that is short for supply and vice versa?
-
What does "remove target" do in Grid Control?
I have some targets that got created during agent installation that aren't real databases. I was wondering what removing the target does. Does it just remove the meta data about the target or if the target is a database will it try to delete the database? Does it modifiy the listener.ora file?
It only deregisters the target and it won't show up in GC.
For e.g. if you remove a database, you won't be able to manage it in Grid Control. It will NOT drop the database on your managed target. -
What is aging report or aging query
hi
i am suresh,
what is aging report or aging query.
can any one tell.Hello Suresh,
Based on the business requirements you design the inventory aging report. Here are few scenarios:
1) Technical Name: 0IC_C03_Q0021
Use
This query displays the inventory aging for selected materials per week and calendar year, and is used in the KPI monitor.
2) Technical Name: 0IC_C01_Q0009
Use
The percentage of total gross inventory (based on value) covered by expected demand within a specific time bucket.
3)
With this picking strategy the system proposes the oldest quant in the storage type as the quant that should be transferred.
The system generally calculates the "age" (length of time in storage) of a quant on the basis of the goods receipt posting date from the Inventory Management (IM) application component. The system automatically sets the goods receipt date in the quant and in the transfer requirement for every goods receipt posting in IM. When the transfer order is created, this date is copied over to the quant record of the destination storage bin.
You can accept the goods receipt date that the system sets or you can enter a different date. Regardless of whether the system proposes the goods receipt date or you enter a different date, the date is used to calculate the age of the quant. This date influences the sorting sequence for each material.
Prerequisites
When you define the storage type record to use this strategy, enter f in the Picking strategy field.
you can find more details in Help.sap.com which fields needs to used etc.
Hope this helps,
Bye,
Naga.
Message was edited by: Naga Timmaraju -
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); -
What are the relation between JPA and Hibernate, JPA and TopLink?
What are the relation between JPA and Hibernate, JPA and TopLink?
Can JPA instead of Hibernate and TopLink?The Java Persistence API (JPA) is the object relational mapping persistence
standard for Java. Hibernate and TopLink provide an Open source Object-relational mapping framework for Java.
They provide an implementation for the Java Persistence API. In my opinion, both Hibernate and TopLink provide support to JPA
and they can also be regarded as the complementary to JPA.
Let's wait to see other person's opinions. -
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 ?
ThanksHi,
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) -
What is the quickest way to query the init.ora?
What is the quickest way to query the init.ora?
Use SHOW PARAMETER at the sql plus prompt.
SQL> show parameter undo
NAME TYPE VALUE
undo_management string AUTO
undo_retention integer 7200
undo_suppress_errors boolean FALSE
undo_tablespace string rollback01
SQL> -
Hi,
is there a way to define 2 jump targets in one query.
For example you have 10 Lines, and the first 5 have one jump target if you click on
a field and will jump to queryT1 and the last 5 lines have another target for the field and will jump to queryT2.
How can I do this, maybe someone knows a tutorial or something...
Thanks
Edited by: alto on Jan 13, 2012 11:24 AMHi
I think u can't achieve that because all that data are present in the same query o/p so how can u jump from one data to another data .
Regards,
RaviChandra -
How to determine what Index is required by a query ?
Hi all,
In our application, we create some complex View with complex query.
The question is : How to determine what Index is required by the query ?
I try using SQL Tuning Advisor, but it seems I can only use it After running TOP SQL.
Is there aniway to determine the Index even Before the query under heavy load/ top sql ?
Thank you very much,
xtantoYou can run your explain plan to check the table access path. You can create an index and see if the optimizer is using the index. Then compare the costs. Creating index will help only in some occassion and you need to provide complete details of the requirement to come to a conclusion of which type of INDEX as well. In some occassions, B*Tree index is useful, in few DW applications, bitmap will work efficiently with columns of low cardinality.
So it is again the task for you to look into this.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/toc.htm
Cheers
Sarma. -
What's the exact difference between "Query Def. Filter Value Selection" and
Hi Gurus,
what's the exact difference between "Query Def. Filter Value Selection" and "Query Execution Filter Val. Selectn" in info-object's "Business explorer" tab?
I found out that if my info-object A has a input-ready variable in a query,after the query running,in the selection screen,my info-object A's F4 value is follow the setting of "Query Execution Filter Val. Selectn",as the setting of "Query Def. Filter Value Selection" I tried every diff setting, it won't effect my query anyway.
so:
1.what's the exact difference between "Query Def. Filter Value Selection" and "Query Execution Filter Val. Selectn" in info-object's "Business explorer" tab?
2.how they effect query's presentation?
I searched forum,didn't find the answer what I want.
Thanks everyone.Hi Denny,
I will try to explain it again.
Query Def. Filter Value Selection : Let say the value is set to "Only Values in Infoprovider"
Lets take an example infoobject - 0MATERIAL (Material)
Total material records in material Master = 1000 (master Data table /BI0/PMATERIAL)
You create a query on top of an Infoprovider using Material.
Total unique materials in Infoprovider= 500.
Now when you are in design mode in Query Designer, and you try to restrict Material by few materials (for e.g. 1, 2, and 3), for this you right click on material and select Restrict, the pop-up opens with list of materials, this list is all those 500 materials which are in the infoprovider, because the setting is "Only Values in Infoprovider". Which means then when you are trying to restrict a characterstic in query definition the list of values displayed for restricition is derived from Infoprovider.
Query Execution Filter Value Selection - I think you already know what it is , its the read mode for F4 help selection.
I hope this helps.
Thanks
CK -
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.
Maybe you are looking for
-
I recently updated to Itunes 12.0.1. Now, when I plug in my Ipod and go to the Music section, the Itunes Match option is unavailable. Which means that my music is taking up too much memory on my Ipod Touch. How do I re-enable the IMatch option so
-
Short dump in RSA3 --Z Data Source
Hi, I created a Z data source based on view and i appended extract structure to insert ZZ fields. When i execute the data source it is showing me short dump how shall i proceed I checked the view conditions and it is extracting data and showing now e
-
ADF:Dynamic Region Refreshing
Hi, My JDeveloper version is 11.1.1.5 I am facing one problem. I have one table to which I have Save and Remove buttons. To the Save button, I have one action which programmatically inserts the row into the table. And Remove button removes the row pr
-
Hi All, In SAP when i am looking into SM12 transaction i am getting one of error for particular background job. Following are those errors which belongs to FI. 1. 00 671: ABAP/4 processor: SAPSQL_ARRAY_INSERT_DUPREC. 2. F1 805: Clearing: Line item 00
-
Hi Can anyone tell me the path where I can find the stylesheet for IE 7.0 I am currently working on ISA Release 10 Regards JM