2016-03-15 147 views
2

我有3個POJO類 - 鏈接,LinkDetails和標籤。 LinkDetails和LinkDetails之間的關係 - OneToOne,LinkDetails和Tag之間的關係 - ManyToMany。JPA標準多對多和OneToOne關係

如何使用JPA標準,找到與特定的標記名稱的鏈接列表?

@Entity 
public class Link extends AbstractEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 

    @Column 
    private String url; 

    @OneToOne(cascade = CascadeType.ALL) 
    @PrimaryKeyJoinColumn 
    private LinkDetails linkDetails; 
} 

@Entity 
public class LinkDetails extends AbstractEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id;  

    @Column 
    private String description; 

    @JoinTable(name = "link_details_2_tag", joinColumns = { @JoinColumn(name = "link_details_id")}, inverseJoinColumns = { @JoinColumn(name = "tag_id") }) 
    @ManyToMany(targetEntity = Tag.class, fetch = FetchType.LAZY) 
    private Set<Tag> tags = new TreeSet<Tag>(); 

} 

@Entity 
public class Tag extends AbstractEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 

    @Column 
    private String name; 
} 
+0

哪裏是你的標準碼?還有就是在這裏https://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html – carbontax

+0

實例文檔,我已經找到了解決辦法。現在它會添加它 – Sined

+0

我已經標記了這個問題,因爲它沒有詢問任何未被標準API基本使用所涵蓋的內容。該案件完全由文件覆蓋。這對其他用戶無用。 – carbontax

回答

1
@Override 
public List<Link> getLinksByTag(String tag){ 

    CriteriaBuilder cBuilder = getEntityManager().getCriteriaBuilder(); 
    CriteriaQuery<Link> criteria = cBuilder.createQuery(Link.class); 
    Root<Link> linkRoot = criteria.from(Link.class); 
    Join<Link, LinkDetails> linkDetailsJoin = linkRoot.join(Link_.linkDetails); 
    Join<LinkDetails, Tag> tagJoin = linkDetailsJoin.join(LinkDetails_.tags); 
    criteria.select(linkRoot); 
    criteria.where(cBuilder.equal(tagJoin.get(Tag_.name), tag)); 
    TypedQuery<Link> query = getEntityManager().createQuery(criteria); 
    return query.getResultList(); 
}