gpt4 book ai didi

java - 将 SQL 映射到谓词

转载 作者:行者123 更新时间:2023-12-02 12:08:35 24 4
gpt4 key购买 nike

我有一些 SQL

select id, name from table where id = '1' and  name = 'A'
or id = '2' and name = 'B'
or id = '3' and name = 'C';

SQL 的结果让我满意,但无论如何我必须将该 SQL 映射到 JPA 的谓词。

我现在拥有的

List<Predicate> predicates = new ArrayList<>();

Predicate id1 = criteriaBuilder.like(root.get(id), "%" + "1" + "%");
predicates.add(criteriaBuilder.and(id1));

Predicate nameA = criteriaBuilder.like(root.get(name), "%" + "A" + "%");
predicates.add(criteriaBuilder.and(nameA));

Predicate id2 = criteriaBuilder.like(root.get(id), "%" + "2" + "%");
predicates.add(criteriaBuilder.and(id2));

Predicate name2 = criteriaBuilder.like(root.get(name), "%" + "B" + "%");
predicates.add(criteriaBuilder.and(name2));

Predicate id3 = criteriaBuilder.like(root.get(id), "%" + "3" + "%");
predicates.add(criteriaBuilder.and(id3));

Predicate name3 = criteriaBuilder.like(root.get(name), "%" + "C" + "%");
predicates.add(criteriaBuilder.and(name3));

query.where(criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query).getResultList();

谓词查询还返回一些冗余数据,SQL 查询除外。

请更正我的谓词条件,以获得与 sql 查询相同的结果。

非常感谢!

最佳答案

我会写类似的东西:

Predicate id1 = criteriaBuilder.like(root.get(id), "%" + "1" + "%");
Predicate nameA = criteriaBuilder.like(root.get(name), "%" + "A" + "%");

Predicate id1nameA = criteriaBuilder.and(id1,nameA);
predicates.add(criteriaBuilder.or(id1nameA));
//...continue for the others

无论如何,使用 like= 不同,因此它可能会产生这样的问题。

If your jpa implementation is Hibernate you can show sql to console by adding the follow lines of code in your persistence.xml

<properties>
<property name="hibernate.dialect" value="..somethinginhere.."/>
<property name="hibernate.show_sql" value="true"/>
</properties>

关于java - 将 SQL 映射到谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46710105/

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