对于ManyToMany和OneToOne关系的Jpa标准

时间:2016-03-15 10:46:29

标签: java jpa many-to-many criteria-api one-to-one

我有3个POJO类 - Link,LinkDetails和Tag。 Link和LinkDetails之间的关系 - OneToOne,LinkDetails和Tag之间的关系 - ManyToMany。

如何使用Jpa Criteria,找到具有指定标签名称的链接列表?

@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;
}

1 个答案:

答案 0 :(得分:2)

@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();
}