Purpose of Eclipselink 2.6.0 query - SELECT ID FROM TBL WHERE ID=? - jpa

Has anyone got an idea why JPA Provider - Eclipselink (using version 2.6.0) generates query like:
SELECT ID FROM OPERATION WHERE (ID = ?);
or
SELECT ID FROM SUBSCRIPTION WHERE (ID = ?);
Why it needs to get ID providing an ID...
Maybe 1st or 2nd level Cache synchronization?
Maybe my queries are inaccurate...
In my queries I never ask directly this to execute - I use JPQL and never ask for ID giving some ID.
I have quite complex model and queries so I see no point in providing full code (or only if U really insist but I dont think it will help a lot).
Using Oracle 12c DB.

We have encountered the same issue with our Java application using EclipseLink 2.5.2. Specifically, we saw it whenever we inserted a new entity that had a M:1 relationship with another entity. A simplified use case would be:
A a = new A(); // the new entity
B b = lookupB(); // get existing entity from database
a.setB(b); // set M:1 relationship
em.persist(a); // save
In this case, we would always see a query for B (i.e., SELECT ID FROM B WHERE ID = #). After some research, we traced it down to the existence checking that EclipseLink performs before merging records.
We found that annotating the entity class for B with #ExistenceChecking(ExistenceType.ASSUME_EXISTENCE) prevented EclipseLink from running the query.
For a further discussion of this, see this related post.

Related

jpa lazy fetch entities over multiple levels with criteria api

I am using JPA2 with it's Criteria API to select my entities from the database. The implementation is OpenJPA on WebSphere Application Server. All my entities are modeled with Fetchtype=Lazy.
I select an entity with some criteria from the database and want to load all nested data from sub-tables at once.
If I have a datamodel where table A is joined oneToMany to table B, I can use a Fetch-clause in my criteria query:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> root = cq.from(A.class);
Fetch<A,B> fetch = root.fetch(A_.elementsOfB, JoinType.LEFT);
This works fine. I get an element A and all of its elements of B are filled correctly.
Now table B has a oneToMany-relationship to table C and I want to load them too. So I add the following statement to my query:
Fetch<B,C> fetch2 = fetch.fetch(B_.elementsOfC, JoinType.LEFT);
But this wont do anything.
Does anybody know how to fetch multi level entities in one query?
It does not work with JPQL and there is no way to make it work in CriteriaQueries either. Specification limits fetched entities to the ones in that are referenced directly from the returned entity:
About fetch join with CriteriaQuery:
An association or attribute referenced by the fetch method must be
referenced from an entity or embeddable that is returned as the result
of the query.
About fetch join in JPQL:
The association referenced by the right side of the FETCH JOIN clause
must be an association or ele ment collection that is referenced from
an entity or embeddable that is returned as a result of the query.
Same limitation is also told in OpenJPA documentation.
For what is worth. I do this all the time and it works just fine.
Several points:
I'm using jpa 2.1, but I'm almost sure it used to work in jpa 2.0 as well.
I'm using the criteria api, and I know some things work diferent in jpql. So don't think it works some way or doesn't work because that's what happens in jpql. Most often they do behave in the same way, but not always.
(Also i'm using plain criteria api, no querydsl or anything. Sometimes it makes a difference)
My associations tend to be SINGULAR_ATTRIBUTE. So maybe that's the problem here. Try a test with the joins in reverse "c.fetch(b).fetch(a)" and see if that works. I know it's not the same, but just to see if it gives you any hint. I'm almost sure I have done it with onetomany left fetch joins too, though.
Yep. I just checked and found it: root.fetch("targets", LEFT).fetch("destinations", LEFT).fetch("internal", LEFT)
This has been working without problems for months, maybe more than a year.
I just run a test and it generates this query:
select -- all fields from all tables
...
from agreement a
left outer join target t on a.id = t.agreement_id
left outer join destination d on t.id = d.target_id
left outer join internal i on d.id = i.destination_id
And returns all rows with all associations with all fields.
Maybe the problem is a different thing. You just say "it wont do anyhting". I don't know if it throws an exception or what, but maybe it executes the query properly but doesn't return the rows you expect because of some conditions or something like that.
You could design a view in the DB joining tables b and c, create the entity and fetchit insted of the original entity.

Entity Framework 4.1 query takes too long (5 seconds) to complete

I have DbContext (called "MyContext") with about 100 DbSets within it.
Among the domain classes, I have a Document class with 10 direct subclasses (like PurchaseOrder, RequestForQuotation etc).
The heirarchy is mapped with a TPT strategy.
That is, in my database, there is a Document table, with other tables like PurchaseOrder, RequestForQuotation for the subclasses.
When I do a query like:
Document document = myContext.Documents.First();
the query took 5 seconds, no matter whether it's the first time I run it or subsequently.
A query like:
Document document = myContext.Documents.Where(o => o.ID == 2);
also took as long.
Is this an issue with EF4.1 (if so, will EF4.2 help) or is this an issue with the query codes?
Did you try using SQL Profile to see what is actually sent to the DB? It could be that you have too many joins on your Document that are not set to lazy load, and so the query has to do all the joins in one go, bringing back too many columns. Try to send a simple query with just one return column.
As you can read here, there are some performance issues regarding TPT in EF.
The EF Team annouced several fixes in the June 2011 CTP, including TPT queries optimization, but they are not included in EF 4.2, as you can read in the comments to this answer.
In the worst case, these fixes will only be released with .NET 4.5. I'm hoping it will be sooner...
I'm not certain that the DbSet exposed by code-first actually using ObjectQuery but you can try to invoke the .ToTraceString() method on them to see what SQL is generated, like so:
var query = myContext.Documents.Where(o => o.ID == 2);
Debug.WriteLine(query.ToTraceString());
Once you get the SQL you can determine whether it's the query or EF which is causing the delay. Depending on the complexity of your base class the query might include a lot of additional columns, which could be avoided using projection. With using projections, you can perform a query like this:
var query = from d in myContext.Documents
where d.ID == 2
select new
{
o.Id
};
This should basically perform a SELECT ID FROM Documents WHERE ID = 2 query and you can measure how long this takes to gain further information. Of course the projected query might not fit your needs but it might get you on the right track. If this still takes up to 5 seconds you should look into performance problems with the database itself rather than EF.
Update
Apparently with code-first you can use .ToString() instead of .ToTraceString(), thanks Slauma for noticing.
I've just had a 5 sec delay in ExecuteFunction, on a stored procedure that runs instantaneously when called from SQL Management Studio. I fixed it by re-writing the procedure.
It appears that EF (and SSRS BTW) tries to do something like a "prepare" on the stored proc and for some (usually complex) procs that can take a very long time.
A quick and dirty solution is to duplicate and then replace your SP parameters with internal variables:
create proc ListOrders(#CountryID int = 3, #MaxOrderCount int = 20)
as
declare #CountryID1 int, #MaxOrderCount1 int
set #CountryID1 = #CountryID
set #MaxOrderCount1 = #MaxOrderCount
select top (#MaxOrderCount1) *
from Orders
where CountryID = #CountryID1

Entity Framework Can't Load Related Entity

Ever since I started using POCO in my projects, I've been having problem querying data that references other entity on the query. The annoying part of it is that trying the same query on LINQPad works well.
For example, this esql query below:
SELECT VALUE TOP(1) a.AccountUrl FROM AppEntities.Accounts AS a WHERE EXISTS(SELECT VALUE u FROM a.Users AS u WHERE u.Username=#username)
throws the follow error when it tries to execute from my application.
Users' is not a member of type 'DelightModel.Account' in the currently loaded schemas. Near simple identifier, line 1, column 104.
I tried the same query on LINQPad with the same dll(Repository library) that my web application referenced, and it worked. Changing the query to return the full entity without projection (example below) also works with no problem.
SELECT VALUE TOP(1) a FROM AppEntities.Accounts AS a WHERE EXISTS(SELECT VALUE u FROM a.Users AS u WHERE u.Username=#username)
The above query work on my application.
Is this a bug or am I doing something wrong?
Please help point me towards the right direction. Thanks.

Doubt regarding JPA namedquery

I am trying to execute a namedquery
#NamedQuery(name="getEmployeeDetails",query="select e.username,e.email,e.image,e.firstname,e.lastname from Employee e where e.empid=?1")
Now when I execute this query in a EJB 3.0 Session Bean what is the object I should return.I tried returning Listits returning a Vector which creates a classcast exception.The employee table contains fields like password and other confidential details which I don't want to fetch.So I am not using select e from Employee e.
I am learning JPA can anyone help.
Below is the sample query which fetches only the required fields, but have to make such constructor for it.
Query : SELECT NEW package_name.Employee(e.username,e.email,e.image,e.firstname,e.lastname) FROM Employee e where e.empid=?1;
It will return Employee entity with selected fields & remaining will have default values.
Inspect the returned type by calling .getClass() on a returned object. I'd guess it's an array.
But this is not really a good way to use JPA. Select the whole entity and then just don't use what you don't need. It's not such a performance hit.

Entity framework linq to entities

Previously when I wanted obtain related data in an sql query I would join tables, however now in linq to entities I want to get data from a table that is related to the table through another table. I don't know how to perform this sort of query in linq to entities. If someone could help that would be good.
The example is a table named person which has a relationship to table users which is related to table roles. I want to be able to obtain a person that has a particular role. Since person is only related to user and indirectly through user to role, I'm not sure of the query. Also using navigation properties doesn't get me all the way there either.
Any information would be good. Here is an example of the database structure:
db structure http://img194.imageshack.us/img194/4540/persons.jpg
If you using the generator in VS (ie, drap drop the data table and diagram and keys are all set in db), then the thing you are asking could be already there automatically.
e.g.
from Person in Context.Persons
where Person.Name == "PETER PAN"
select Person.User.Role.RoleName;
Exact name need to refer to the code generator, but this is the idea. Linq to entities will help to map foreign keys and those for you.
Edit
Actually I haven't tried using include. But according to msdn:include method, the include should show the object hierarchy to work. So, for your query to work, try:
from c in db.Persons.Include("aspnet_Users").Include("aspnet_Roles")
where c.aspnet_Users.aspnet_Roles.RoleName == "Role" select c
And moreover, will you consider start from roles?
from r in db.aspnet_Roles
where r.RoleName == "ROLE"
select r.aspnet_Users.Persons
(from u in db.aspnet_Users.Include("Person")
from c in db.aspnet_Roles
where c.RoleName == "role"
select u.Persons);
Worked it out thanks for trying though.