gpt4 book ai didi

java - JPA Criteria 根据条件过滤集合

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

为什么 Criteria 查询不基于服务(集合实体)条件services.get("status"), "pending")过滤记录,如下所示?

CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
Root<Customer> customer = query.from(Customer.class);
Join<Customer, Service> services = customer.join("services", JoinType.INNER);

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

predicates.add(cb.equal(customer.get("customerId"), 1));
predicates.add(cb.equal(services.get("status"), "pending"));

query.select(customer).distinct(true)
.where(predicates.toArray(new Predicate[]{}));

List<Customer> customers = em.createQuery(query).getResultList();

SQL 正确过滤记录的位置

  select * from customers c
INNER JOIN SERVICES s on s.COID = c.COID
where c.ID=1 and
s.status='pending';

根据状态条件(用于收集),结果集中的记录不合格,实际上,客户的所有服务都被退回。

我尝试使用 fetch Join (因为第一个为客户执行了 2 个查询,第二个为该客户的服务执行了第二个查询,认为第二个查询中可能不会评估条件)使用

customer.fetch("services", JoinType.INNER);

但运气不好。

我对这种行为感到惊讶。我正在使用 OpenJPA JPA 提供程序

实体是客户服务

 public class Customer{
@Id
@Column(name = "ID")
private Integer customerId;
@OneToMany
@MappedBy(name = "customer")
private List<Service> services;
}

public class Service {
@EmbeddedId
private ServicesPK servicePK;
@ManyToOne
@JoinColumn(name = "COID")
private Customer customer;
}

@Embeddable
@EqualsAndHashCode
public class ServicesPK implements Serializable {
@Column(name = "COID")
private Integer coId;
@Column(name = "VERSION")
private Integer version;
}

最佳答案

尝试这段代码,我所做的更改是我向查询添加了类型安全。了解类型安全 typesafe

CriteriaQuery<Customer> query = cb.createQuery(Customer.class);
Root<Customer> customer = query.from(Customer.class);
Join<Customer, Service> services = customer.join(Customer_.services);
List<Predicate> predicates = new ArrayList<Predicate>();

predicates.add(cb.equal(customer.get("customerId"), 1));
predicates.add(cb.equal(services.get(Service_.status), "pending"));

query.select(customer).distinct(true)
.where(predicates.toArray(new Predicate[]{}));

List<Customer> customers = em.createQuery(query).getResultList();

关于java - JPA Criteria 根据条件过滤集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45474061/

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