亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

CrudRepositry 使用@Query 檢查集合是否包含一個項目

CrudRepositry 使用@Query 檢查集合是否包含一個項目

呼喚遠方 2021-08-04 17:21:16
我不知道如何檢查我的數據庫中是否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 連接將自動連接正確的鍵,否則會出現錯誤。


然后您可以照常指定條件。


查看完整回答
反對 回復 2021-08-04
  • 1 回答
  • 0 關注
  • 224 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號