gpt4 book ai didi

java - 如何使用 LEFT OUTER JOIN 创建 JPA 查询?

转载 作者:行者123 更新时间:2023-11-30 05:49:35 27 4
gpt4 key购买 nike

我正在学习 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查询码呢?谢谢

最佳答案

如果您使用的是 spring data jpa,您可以在存储库层中提供它,例如:

@Repository
public interface CategoryRepository extends JpaRepository<Category, Integer> {
@Query( value =
"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'",
nativeQuery = true)
List<Category> fetchCategoryDataLeftJoin();

}

关于java - 如何使用 LEFT OUTER JOIN 创建 JPA 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com