简体   繁体   English

如何编写休眠OneToMany关系的hql查询?

[英]how to write hql query for hibernate OneToMany relationship?

I have the following classes laid out like so: 我的班级安排如下:

class User {
    @Id
    private long id;

    @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    Set<UserRole> userRoles;
}

class UserRole {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private int id;

    @Column(name = "role", nullable = false, length = 45)
    private String role;
   }

I'm attempting to query for users that have a specific role (in this case, all users with the role ROLE_ADMIN), using the following query: 我正在尝试使用以下查询来查询具有特定角色的用户(在这种情况下,所有具有ROLE_ADMIN角色的用户):

    org.hibernate.query.Query<User> userQuery=session.createQuery("from User as mc where mc.userRoles in (from UserRole as ur where ur.role in (:uRoles))",User.class);
    Set<String> roles = new HashSet<String>();
    roles.add("ROLE_ADMIN");
    userQuery.setParameterList("uRoles", roles);
    List<User> admins = userQuery.getResultList();

However, the query is not returning any results. 但是,查询不返回任何结果。

session.createQuery(
  "from User as user join user.userRoles as userRole where userRole.role in :roles")
  .setParameter("roles", Arrays.asList("ROLE_ADMIN"))
  .getResultList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM