[英]Custom Query Join in JPA using Criteria Builder API
目前我正在这样做:
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity) {
String queryString = "SELECT table1.* FROM table1 "
+ "JOIN table2 t2 ON table1.id=t2.table1_id";
if (table1Entity.getName() != null) {
queryString +=" where name like ?";
}
Query query = em.createNativeQuery(queryString, Table1Entity.class);
if (table1Entity.getName() != null) {
query.setParameter(1, table1Entity.getName())
}
return query.getResultedList();
}
如果我想在这个连接中检查更多参数,这将很快变成很多 if 语句,并且正确设置参数会非常复杂。
我知道我可以使用标准 Builder API 来检查参数,如下所示:
if(table1Entity.getName() != null) {
table1EntitySpecification = (root, query, criteriaBuilder)
-> criteriaBuilder.like(
criteriaBuilder.lower(root
.get("name")),
("%" + table1Entity.getName() + "%")
.toLowerCase());;
}
然后让他们全部获得:
findAll(table1EntitySpecification)
和来自simpleJPARepository
的findAll
。 现在我可以将它们与.or
或.and
等链接在一起,避免第二次设置参数和检查null
。
但是我该如何加入criteria APi
?
我知道我可以在我的@Repository
中有这样的东西:
@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
但由于name
是可选的(可以是null
),我不能只将它留在@Query
中。
避免使用本机查询以及必须检查许多参数以避免使用if
语句的最佳解决方案是什么?
我不知道我是否完全得到你的问题,但关于空值的可能性,以及使用 CRUD 存储库,你总是可以像之前一样做一个 null 检查:
@Query(value = "SELECT table1.* FROM table1 JOIN table2 t2 ON table1.id=t2.table1_id WHERE table1.id is not null", nativeQuery = true)
List<Table1Entity> findAllMatchingEntities(Table1Entity table1Entity);
根据您要实现的目标,您始终可以使用类似的检查来编写查询,例如(与您的代码无关):
@Query("SELECT c FROM Certificate c WHERE (:id is null or upper(c.id) = :id) "
+ "and (:name is null or upper(c.name) = :name)")
List<Table1> findStuff(@Param("id") String id,
@Param("name") String name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.