从多对多关系中获取结果

时间:2017-04-13 19:21:03

标签: java hibernate many-to-many

我有两个实体很多很多关系,如下所示..

@Entity
@Table(name = "MEMBER")
public class Member implements Serializable {
    @Id
    private Long id;

    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @Fetch(value = FetchMode.SELECT)
    @JoinTable(name = "MEMBER_BADGE",
            joinColumns = {@JoinColumn(name = "member_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name = "badge_id", referencedColumnName = "id")})
    private List<Badge> badgeList = new ArrayList<>(0);

    // Getter & Setters

}

@Entity
@Table(name = "BADGE")
public class Badge implements Serializable{
    @Id
    private Long id;

    private String name;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "badgeList")
    @Fetch(FetchMode.SELECT)
    private List<Member> memberList = new ArrayList<>(0);

    // Getter & Setters
}

Badge名称示例...&#34; 教师&#34;,&#34; 医生&#34;,&#34 ;的工程师&#34;等

如何获得所有&#34; List<Member> &#34;谁拥有&#34; 老师&#34; Hibernate徽章Criteria/Query

session.createCriteria(Member.class).add(Restrictions.eq(---What ?---)).list();

session.createQuery("select mem from Member where ???? ").list();

1 个答案:

答案 0 :(得分:0)

它已使用别名......

解决
session.createCriteria(Member.class)
       .createAlias("badgeList", "badge")
       .add(Restrictions.eq("badge.name", "Teacher"))
       .list();