I use JPA with Hibernate implementation. My question is probably basic for experienced hibernate users: what is the most efficient way to write queries based on Hibernate first level cache?
For example, I have entity A and entity B:
@Entity
class A{
private int ida;
private int x;
private String s;
@OneToMany(mappedBy = "ida", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<B> Bset;
}
@Entity
class B{
private int ida;
private String s2;
}
Suppose I have several flows that may happen in the same session:
- get
A.x - get the whole
Aentity - check if
AcontainsBwiths2="...";
For every one of these queries I can
- write a specific query that gets
A.x/Bbyidaands2
or - suppose that Hibernate saves cache and always get
Aobject, orA.Bset()and then java loops to get the neededBinsideBset()
What is the most efficient way?
thank you
For use cases 1 and 2 I would just load the whole entity. Second level cache will work equally well. Unless your
Aobject is really big (has a lot of properties) you won’t see see any difference compared to:Even worse, using the query above will not take advantage of L2 cache.
Third use case is more interesting. It heavily depends on your requirements, but the reasonable balance would be to use a query like this:
If the query returns something it means
acontainsbwith givens2. This should be much faster than lazily loadingBsetand iterating over it. Consider enabling query cache.However if
Bsetis typically small and you use eager fetching, simple filtering in Java might be better. It really depends on your architecture.