[英]Spring Boot JPA query for retrieve data from many to many Relationship Table
我需要從 role_id =2 的用戶表中檢索用戶。 這就是實體之間的關系。
以下 MySQL 查詢完美運行。並檢索 role_id = 2 的用戶。
select * from users INNER JOIN user_roles ON users.id = user_roles.user_id INNER JOIN roles ON roles.id = user_roles.role_id WHERE role_id='2';
但我需要在 spring 引導應用程序中執行此操作,這是實現的存儲庫。
@Query("select usr from User usr INNER JOIN user_roles ur "+
"ON usr.id = ur.user_id INNER JOIN Role roles " +
"ON roles.id = ur.role_id WHERE ur.role_id='2' AND usr.department=(:depId)")
List<User> findAll(@Param("depId") Long depId);
但是 user_roles 不是一個實體,上面的查詢不起作用。 是否有解決方案或任何其他方式來實現我的目標?
這是您嘗試從程序內部使用的查詢。
SELECT usr
FROM User usr
INNER JOIN user_roles ur ON usr.id = ur.user_id
INNER JOIN Role roles ON roles.id = ur.role_id
WHERE ur.role_id='2'
AND usr.department=(:depId)
您在SELECT
子句中提到的usr
不是任何表中的列。 也許您應該嘗試usr.*
而不是從匹配的User
表中獲取所有列。
而且,您不需要加入Role
表來獲取role_id
; 它在user_roles
表中。 所以,試試這個。
SELECT usr.*
FROM User usr
INNER JOIN user_roles ur ON usr.id = ur.user_id
WHERE ur.role_id='2'
AND usr.department=(:depId)
專業提示能夠查看程序中嵌入的查詢並對其進行推理非常重要。 在源代碼中仔細格式化它們是值得的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.