Reputation: 7021
May we find an entity using entitymanager using the foreign key associated to it?
For example I have a class like this :
@Entity
@Table(name = "shopping_bag")
public class ShoppingBag {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
@OneToOne
private Member member;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private Set<Product> product = new HashSet<Product>();
}
Where Member is like this :
@Entity
@Table(name = "shopping_member")
public class Member {
@Id
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
}
What I'm trying to do is to get all Products knowing a Member id using entityManager!
A solution is to use Native SQL - or HSQL however I want to know if there is a more simple solution ... Any Idea ?
Upvotes: 2
Views: 1822
Reputation: 11531
You clearly cannot use find()
since that finds an object of a type with an id (as its javadoc tells you clear enough).
You can do a JPQL
query to get what you want.
SELECT p FROM ShoppingBag b JOIN b.product p JOIN b.member m WHERE m.id = :memberId
Upvotes: 1
Reputation: 31901
You can use Hibernate Criteria
List results = entityManager.createCriteria(ShoppingBag.class, "ShoppingBag")
.createAlias("ShoppingBag.member", "member", Criteria.LEFT_JOIN);
.add( Restrictions.eq("member.id", someStringValue) )
.list();
Upvotes: 2