1

我需要得到的都是Events where CustomerEvent.customer.id = 123。我实际上得到的是例外。

仅具有相关成员的简化实体:

@Table(name = "EVENT")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING, length = 1)
public abstract class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(nullable = false)
    private Integer id;
}

@Entity
@DiscriminatorValue("C")
public class CustomerEvent extends Event {
    @ManyToOne(optional = false)
    private Customer customer;
}

@Entity
@Table(name = "CUSTOMER")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(nullable = false)
    private Integer id;

}

询问:

final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<Event> cq = cb.createQuery(Event.class);
final Root<Event> root = cq.from(Event.class);
cq.select(root);
cq.where(cb.equal(((Root<CustomerEvent>) root.as(CustomerEvent.class)).get(CustomerEvent_.customer).get(Customer_.id), 123));

// this predicate doesn't work either: cb.isNotNull(((Root<CustomerEvent>) root.as(CustomerEvent.class)).get(CustomerEvent_.customer));

em.createQuery(cq).getResultList(); // throws exception

例外:

Exception [EclipseLink-6015] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.QueryException
Exception Description: Invalid query key [customer] in expression.
Query: ReadAllQuery(referenceClass=Event )
    at org.eclipse.persistence.exceptions.QueryException.invalidQueryKeyInExpression(QueryException.java:691)
4

1 回答 1

1

如果您使用的是 root.as(CustomerEvent.class),为什么不直接查询 CustomerEvent?只有 CustomerEvent 实例可以有 CustomerEvent.customer.id = 123 或者你不需要使用'as'函数。

'As' 已被弃用,而应使用 JPA 的 Treat 谓词(包含在 EclipseLink 2.5.1 中) - 不同之处在于,treat 将排除该谓词中的非 customerEvent 实例,而 'as' 仅强制转换谓词,因此更加困难使用起来不太稳定。Treat 允许您安全地使用更复杂的表达式,例如“Select event from Event event where (treat(event as CustomerEvent).customer.id = 123) or event.somethingelse = someotherCondition”

于 2014-04-09T15:21:59.717 回答