简体   繁体   English

使用Criteria Api按嵌套字段排序时缺少行

[英]Missing rows when ordering by nested field using Criteria Api

I've encounterd weird behaviour of JPA (provider: EclipseLink) using order by functionality. 我遇到了按功能排序的JPA(提供者:EclipseLink)的怪异行为。 I have TransactionData class, which has reference to CustomerData class: 我有TransactionData类,它引用了CustomerData类:

@Entity
public class TransactionData {
    //...
    @ManyToOne
    @JoinColumn(name = "CUSTOMER_ID")
    private CustomerData customer;
    //...
}

@Entity
public class CustomerData {
    //...
    @Column(name = "LAST_NAME")
    private String lastName;
    //...
}

In my project, there are some specific cases, where there are transactions, which are not assigned to any customer (called non-customer transactions). 在我的项目中,有一些特定的情况,其中有未分配给任何客户的交易(称为非客户交易)。

I try to get list of all registered transactions (both cusotmer transactions and non-customer transactions) and sort them by customer's last name. 我尝试获取所有已注册交易(客户交易和非客户交易)的列表,并按客户的姓氏对其进行排序。 To acheive this I've written following Criteria Api 为了达到这个目的,我按照Criteria Api编写

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransactionData> criteriaQuery = criteriaBuilder.createQuery(TransactionData.class);
Root<TransactionData> from = criteriaQuery.from(TransactionData.class);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("customer").get("lastName"));
TypedQuery<TransactionData> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();

I think I should get list of all transactions, of course, with those, where customer field is set to NULL value. 我想我应该获得所有交易的清单,当然,其中客户字段设置为NULL值的交易也是如此。 But JPA behaviour is different, because it cut out all transactions, where reference to customer is empty. 但是JPA的行为有所不同,因为它切断了所有对客户的引用为空的交易。

from.get("customer").get("lastName") will do implicitly an INNER JOIN. from.get("customer").get("lastName")将隐式执行INNER JOIN。 If some transactions have no customer assigned then what you need is a LEFT JOIN: 如果某些交易没有分配客户,那么您需要的是LEFT JOIN:

Join<TransactionData , CustomerData> customer = from.join("customer", JoinType.LEFT);
criteriaQuery.orderBy(criteriaBuilder.asc(customer.get("lastName"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM