我不知道如何檢查我的數據庫中是否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
提交
取消