gpt4 book ai didi

jpa - 如何使用 Criteria Query 获取相交查询?

转载 作者:行者123 更新时间:2023-12-02 17:45:20 25 4
gpt4 key购买 nike

给定

 @Entity
public class Document {

@Id
@Column(name = "DOCUMENT_ID")
private Long id;

@ElementCollection
@CollectionTable(
name="TAG",
joinColumns=@JoinColumn(name="DOCUMENT_ID")
)
@Column(name="TAG")
private Set<String> tags;
}

查找所有标记有特定标签集合的文档。本质上,EclipseLink 等效于:

SELECT d FROM Document d WHERE :tag1 MEMBER OF d.tags
INTERSECT
SELECT d FROM Document d WHERE :tag2 MEMBER OF d.tags
...
SELECT d FROM Document d WHERE :tagn MEMBER OF d.tags

但使用 JPA CritieraQuery。

最佳答案

使用带有 having 子句的聚合查询来选择与所有必需标记匹配的行:

    CriteriaBuilder cb = entityManager().getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
Root<Document> from = q.from(Document.class);
List<Predicate> predicates = new ArrayList<Predicate>();
Expression<Long> id = from.get("id");

Expression<Collection<String>> documentTags = from.get("tags");
for (String tag : searchedTags) {
Expression<String> param = cb.literal(tag);
Predicate predicate = cb.isMember(param, documentTags);
predicates.add(predicate);
}

q.multiselect(id).where(
cb.or(predicates.toArray(new Predicate[0])));
q.distinct(true);
q.groupBy(id);

q.having(cb.equal(cb.count(id), searchedTags.size()));

TypedQuery<Long> query = entityManager().createQuery(q);

关于jpa - 如何使用 Criteria Query 获取相交查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690791/

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