Reputation: 9266
Suppose I have the following 2 entities:
@Entity
public class Person implements Serializable {
private Long id;
@OneToMany(fetch=FetchType.LAZY)
private List<House> houses;
}
@Entity
public class House implements Serializable {
private Long id;
private List<House> houses;
}
Suppose the house I am looking for exists and I have both personID
and houseID
, which one of the followings should be faster or cost less resources and why?
House house = em.find(House.class, id);
or
Query q = em.createQuery("SELECT H FROM Person P JOIN P.houses H
WHERE C.id = :personID AND H.id = :houseID");
The 2nd query seems to narrow down the search but I didn't know if it's faster.
I'd be very grateful if you could give me an advice.
Upvotes: 0
Views: 96
Reputation: 1
When you create a SQLqurey it always creates a new object with the connection Open with the database, but while searching it trough JPA by primary key, JPA bydefault creates SQL indexes for the primary key, and we know that indexes are used for efficient searching so it always faster and efficient way than the directly firing query on database. so for the better performance and speed always use, _em.find(class,primary_key) instead of creating query.
Upvotes: 0
Reputation: 597274
If you want to find a house, you don't need to query for a Person. So the first option. Your 2nd option has an additional requirement - a specific person to own that house.
On a general note - it is always faster to look up by primary key than by a query (unless the query is also by just primary key)
Upvotes: 2