How do i enforce lazy loading strategy just for a given NamedQuery.
for eg. Consider the below pseudo code (just to explain the case) I have an entity
@Entity
class Xyz {
int a;
int b;
@Fetch = EAGER
Set<ABC> listOfItems;
}
In this case, we have declared listOfItems to be EAGERLY fetched.
Now suppose , I have an NamedQuery (query="getXyz" , name="select x from Xyz x where a=?")
For this query , i just need the result to be lazy i.e i dont want the listOfItems to be retrieved.
What are the ways by which i can acheive them ?
p.s :
1. I dont want to change the listOfItems to be Lazy in the Entity class
2. I dont want to select specific fields in the query like name="select a,b from Xyz z where a = ? "
Thanks in advance for the suggestions
If you don't want to fetch the Set
eagerly you have to define it as lazy. However note that the implementation is permitted to fetch eagerly when you specify lazy.
Quoting the specification:
public enum FetchType extends java.lang.Enum
Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified.
If you however don't want to fetch such a Set
I would as an alternative create a small class to fit your needs:
@Entity
@Table(name = "XYZ")
public class XyzStub
{
int a;
int b;
}
You can query for this using a TypedQuery:
EntityManager em;
//....
TypedQuery<XyzStub> q = em.createNamedQuery("select x from XyzStub x where x.a = :a", XyzStub.class)
q.setParameter("a", a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With