我的User
实体已映射到user_roles
。我想根据User.id
和roles.name
与此SQL查询相同
SELECT ur
FROM user
JOIN user_roles ur
ON ur.user_id = user.id
WHERE user.id = 1
AND ur.name like '%admin%';
如何在hibernate中实现这个SQL查询? 如何将参数传递给角色名?
User.java
@Entity
class User {
@ManyToMany
@JoinTable(name="user_roles",
joinColumns=@JoinColumn(
name="user_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(
name="role_id", referencedColumnName="id")
)
public Set<Role> getRoles() {
return roles;
}
}
答案 0 :(得分:1)
希望它会有所帮助
select "your_req" from User us join usr.role usr where usr.name like '%admin%' and us.id=1
答案 1 :(得分:0)
HQL完全支持您的需求,您可以创建HQL查询,然后将参数传递给它。以下代码块可能是参考:
Long userId = 1L;
String roleNamePattern = "%admin%";
Query query = session.createQuery("SELECT role FROM User user JOIN user.roles role WHERE user.id = :userid AND role.name LIKE :rolename");
query.setLong("userid", userId);
query.setString("rolename", roleNamePattern);
List<Role> roles = query.list();