我有 3 个 bean:组织、角色、用户
角色 - 组织关系 - @ManyToOne
角色 - 用户关系 - @ManyToMany
组织 :
@Entity
@Table(name = "entity_organization")
public class Organization implements Serializable {
private static final long serialVersionUID = -646783073824774092L;
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
Long id;
String name;
@OneToMany(targetEntity = Role.class, mappedBy = "organization")
List<Role> roleList;
...
角色 :
@Entity
@Table(name = "entity_role")
public class Role implements Serializable {
private static final long serialVersionUID = -8468851370626652688L;
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
Long id;
String name;
String description;
@ManyToOne
Organization organization;
...
用户:
@Entity
@Table(name = "entity_user")
public class User implements Serializable {
private static final long serialVersionUID = -4353850485035153638L;
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
Long id;
@ManyToMany
@JoinTable(name = "entity_user_role",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
List<Role> roleList;
...
所以我需要获取指定用户的所有组织(首先我需要选择所有用户角色,然后选择所有具有此角色的组织)
我有一个实现此逻辑的 sql 语句(例如,我选择 id = 1 的用户):
SELECT * FROM entity_organization AS o
INNER JOIN entity_role r ON r.organization_id = o.id
INNER JOIN entity_user_role ur ON ur.role_id=r.id
WHERE ur.user_id = 1
如何使用休眠命名查询机制来实现这一点?谢谢!