来自 3 列连接的 JPA 查询 table

JPA Query from 3 column join table

我有以下实体。意味着用户可以属于许多企业,并且对于每个企业,该用户可以拥有单独的权限。因此,可以将现有用户分配给另一家企业。 Business_User table 看起来像这样:

USER_ID  BUSINESS_ID    AUTHORITY_NAME  
6         1             ROLE_ANALYTICS
6         1             ROLE_SELF_ANALYTICS
7         1             ROLE_REVIEWS
8         1             ROLE_ANALYTICS
8         1             ROLE_SELF_ANALYTICS
8         1             ROLE_REVIEWS
6         2             ROLE_REVIEWS
6         2             ROLE_SELF_ANALYTICS

问题:我正在通过尝试构建用户 DTO 对象列表来查询用户的一项业务,DTO 公开了 List<Authority>,问题是我不能想一想我应该如何从 Business_User table 中为每个用户获取这些权限。一直在尝试用 lambda 做一些花哨的事情,但没有运气。我正在使用 Spring 数据进行查询,也许可以在存储库中解决它。

提前致谢。

编辑:如果我要通过添加新加入 table BUSINESS_USER_AUTHORITY 走另一条路,我将如何在 [=18= 中描述它] class?我也希望主键超过 user_id 和 business_id。注意nameAuthoritytable.

中的PK

类似这样的事情,但这并没有让我加入 table。

更改用户业务 class:

  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(
      name = "BUSINESS_USER_AUTHORITY",
      joinColumns = {@JoinColumn(name = "business_user_id", referencedColumnName = "id")},
      inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
  private Set<Authority> authorities = new HashSet<>();

用户

@Entity
@Table(name = "USER")
public class User extends AbstractAuditingEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumns({
    @JoinColumn(name = "user_id", referencedColumnName = "id")
  })
  private Set<BusinessUser> businessUsers = new HashSet<>();
}

企业用户

@Entity
@Table(name = "BUSINESS_USER")
@IdClass(BusinessUser.class)
public class BusinessUser implements Serializable {

  @Id
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "user_id")
  private User user;

  @Id
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "business_id")
  private Business business;

  @Id
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "authority_name")
  private Authority authority;

}

商业

@Entity
@Table(name = "BUSINESS")
public class Business implements Serializable {

  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumns({
    @JoinColumn(name = "business_id", referencedColumnName = "id")
  })
  private Set<BusinessUser> businessUsers = new HashSet<>();

}

权限

@Entity
@Table(name = "AUTHORITY")
public class Authority implements Serializable {

  @NotNull
  @Size(min = 0, max = 50)
  @Id
  @Column(length = 50)
  private String name;
}

我最终写了一个这样的函数,但如果有人有解决方案,设计在 BusinessUser <--> BusinessUserAuthority 之间的另一个连接 table 看起来如何,那么我很乐意实施它。

  private Function<Map.Entry<User, List<BusinessUser>>, UserManagementDTO> getPermissionForUser() {
    return user -> {
      UserManagementDTO dto = userManagementMapper.userToUserManagementDTO(user.getKey());
      dto.setAuthorities(user.getValue().stream().map(BusinessUser::getAuthority).collect(Collectors.toSet()));
      return dto;
    };
  }