我正在学习JPA,所以我想使用这样的mysql查询
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1 LEFT
JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ROOT'
那么如何将其更改为jpql查询代码?谢谢
如果您使用的是EntityManager,则可以按照这种方式进行操作
@PersistenceContext private EntityManager entityManager;
StringBuilder sb = new StringBuilder();
sb.append("SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1 LEFT
JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = :name"); // :name - you can pass parameter here
Query q = entityManager.createQuery(sb.toString());
q.setParameter("name", "ROOT");//Root is the value and name is the parameter
如果使用的是Spring数据jpa,则可以在存储库层中提供它,如:
@Repository
public interface CategoryRepository extends JpaRepository<Category, Integer> {
@Query(
"SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1" +
"LEFT JOIN category AS t2 ON t2.parent = t1.category_id" +
"LEFT JOIN category AS t3 ON t3.parent = t2.category_id" +
"LEFT JOIN category AS t4 ON t4.parent = t3.category_id" +
"WHERE t1.name = 'ROOT'")
List<DeptEmpDto> fetchCategoryDataLeftJoin();
}