2014-06-10 37 views
0

我有這個實體product,我想加入自己創建一個組,並有權訪問該組的其他成員,當我有任何成員和一個產品可以只在一個組或一個都沒有,嘗試來測試這一點:如何自我加入實體以使用JPA創建一組實體?

@Entity 
@Table(name = "product") 
public class Product { 

@Id 
@GeneratedValue 
private Long id; 

@Column 
private String name; 
@Column 
private Long groupId; 

@OneToMany 
@JoinColumn(name = "groupId") 
private List<Product> group; 
  • 我可以編寫一個名爲group另一個實體,並使用該加入,但就是因爲這group最好的辦法只能承受一個ID,我正在尋找的最佳實踐這裏,謝謝

回答

0

無法在JPA中完成JPA restr icts外鍵引用ID字段,而您希望groupId指定組中的其他內容。您可以將組設爲瞬態,而是懶惰地使用查詢從實體管理器中獲取它:

@Transient 
private List<Product> group; 

public List<Product> getGroup(EntityManager em) { 
    if (group==null) { 
    group = em.createQuery("Select p from Product p where p.groupId = :groupId").setParameter("groupId", this.getGroupId()).getResultList(); 
    } 
    return group; 
} 
相關問題