ManyToMany在JPA2(JPQL)中选择查询

时间:2016-03-21 13:05:07

标签: many-to-many criteria jpql

我有两个表:ManyToMany关系中的用户和角色。

@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;

    @ManyToMany
    @JoinTable(name = "user_role",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

//getters, setters
}

@Entity
@Table(name = "role")
public class Role implements Serializable {

    @Id
    @Column(name = "role_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long roleId;

    @Column(name = "role_code")
    private String roleCode;


    @ManyToMany(mappedBy = "roles")
    @JsonIgnore
    private Set<User> users;

//getters,setters

}

如果用户有角色,我希望选择所有用户和所有HIS角色,例如&#39; ROLE_USER&#39;。

我在原生sql中做过,但我想使用JPQL或CriteriaQuery。

我在JPQL中尝试过(在子查询中将早期的提取类型更改为EAGER,我无法使用连接提取):

public List<User> findUsersByRole(String roleName, int startNumber, int endNumber) {
    Query q = em.createQuery("select u from User u join fetch u.roles r WHERE u.userId in (SELECT uu.userId FROM User uu join uu.roles rr WHERE rr.roleCode like :roleName)")
            .setParameter("roleName", roleName)
            .setFirstResult(startNumber)
            .setMaxResults(endNumber);
    return q.getResultList();
} 

它可以按照我的意愿工作,但是可以不将Fetching类型更改为EAGER吗? 谢谢你的回复。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

public List<User> findUsersByRole(String roleName, int startNumber, int endNumber) {
    Query q = em.createQuery("select u from User u join fetch u.roles join u.roles r WHERE r.roleCode like :roleName")
            .setParameter("roleName", roleName)
            .setFirstResult(startNumber)
            .setMaxResults(endNumber);
    return q.getResultList();
}