我不知道如何检查我的数据库中是否User有某个Role。具体来说,我想运行一个计数查询 - 并希望避免在数据库之外进行处理。我们的代码库使用org.springframework.data.repository.CrudRepository- 因此我们@Query用来指定复杂的查询。( org.springframework.data.jpa.repository.Query)此 SQL 查询返回我想要的内容:SELECT Count(*) FROM user where id in ( select user_id from user_role where role_type = 'ROLE_USER');但我无法得到我@Query想要的回报。这是一些代码:User 班级:@Entity@ApiModel(description = "Represents an user of the system")public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "ID") @ApiModelProperty(value = "The ID of the user", required = true) private Long id; @Column(name = "USERNAME", unique = true) @ApiModelProperty(value = "The userName of the user", required = true) private String username; @Column(name = "STATUS", nullable=false) @Enumerated(EnumType.STRING) @ApiModelProperty(value = "The status of the user", required = true) private UserStatus status; @Column(name = "PASSWORD") @ApiModelProperty(value = "The encrypted password of the user") private String password; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "USER_ID", nullable=false) @ApiModelProperty(value = "The role of the user", required = true) private Set<UserRole> userRoles;}UserRole 班级:@Entitypublic class UserRole implements Serializable { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "ROLE_TYPE") @Enumerated(EnumType.STRING) private UserRoleType roleType; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "USER_ID", nullable=false, insertable=false, updatable=false) @ApiModelProperty(value = "The id the user (link to User table)", required = true) private User user;}数据库非常简单,包含User表和User_Role表。该User表有Id, Username, Password,Status列。
1 回答
凤凰求蛊
TA贡献1825条经验 获得超4个赞
您可以使用存储库界面中的一个简单函数来解决此问题:
long countByStatusAndUserRoles_roleType(status: UserStatus, roleType: UserRoleType)
这个查询应该做同样的事情:
@Query("select count(u) from User u left join u.userRoles ur where u.status = :status and ur.roleType = :roleType")
long countAllActiveUser(status: UserStatus, roleType: UserRoleType);
您当然可以硬编码status和roleType.
所以你首先需要加入实体(表)。我选择了左连接,因为您需要来自两个实体的项目,有关连接类型的更详细答案,请参见此处。如果通过上下文给出,JPA 连接将自动连接正确的键,否则会出现错误。
然后您可以照常指定条件。
添加回答
举报
0/150
提交
取消