在Spring Data JPA中使用多个表连接Query

时间:2018-04-29 13:22:48

标签: spring jpa join spring-data spring-data-jpa

我已经实现了@ManyToMany关系,但是在用户角色权限和额外的表之间使用了@OneToMany和@ManyToOne的额外表格“的的UserRole ”, “ RolePermissions

一个用户可以拥有多个角色,一个角色也可以拥有多个权限。我必须在角色的基础上获得用户的权限。所以我写了一个工作正常的查询

id

这个查询看起来很冗长,我希望尽可能简短或优化它。

实体正在关注

@Query("SELECT DISTINCT p FROM Permission p INNER JOIN p.roles rp INNER JOIN rp.role r INNER JOIN r.users ur INNER JOIN ur.user u WHERE u.id=:userId")
List<Permission> findAllUserRolePermissions(@Param("userId") long userId);

我想要什么?

1)这个查询好吗?或者可以改进,如果是,那么如何?

2)我可以使用如下的弹簧数据接口方法实现这一点

@Entity
@Table(name = "USER")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

    @JsonIgnore
    @OneToMany(targetEntity = UserRole.class, mappedBy = "user", fetch = FetchType.LAZY)
    private List<UserRole> roles;


//Role
@Entity
@Table(name = "Role")
public class Role implements Serializable {
@OneToMany(targetEntity = UserRole.class, mappedBy = "role", fetch = FetchType.LAZY)
    private List<UserRole> users;

    @OneToMany(targetEntity = RolePermission.class, mappedBy = "role", fetch = FetchType.LAZY)
    private List<RolePermission> rolePermissions;

//Use_Role  
@Entity
@Table(name = "USER_ROLE")
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserRole {

    @ManyToOne
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne
    @JoinColumn(name = "ROLE_ID")
    private Role role;



//Permission

@Entity
@Table(name = "PERMISSION")
public class Permission {

    @OneToMany(targetEntity = RolePermission.class, mappedBy = "permission", fetch = FetchType.LAZY)
    private List<RolePermission> roles;


//Role_Permission
@Entity
@Table(name = "ROLE_PERMISSION")
@JsonIgnoreProperties(ignoreUnknown = true)
public class RolePermission {

    @ManyToOne
    @JoinColumn(name = "ROLE_ID")
    private Role role;

    @ManyToOne
    @JoinColumn(name = "PERMISSION_ID")
    private Permission permission;

3)学习spring数据jpa join查询的任何资源

任何建议都会受到赞赏。谢谢

0 个答案:

没有答案