EclipseLink-6015表达式中的查询键[customer]无效

时间:2014-04-09 14:54:38

标签: jpa eclipselink jpa-2.1

我需要得到的是Event所有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)

1 个答案:

答案 0 :(得分:1)

如果您使用的是root.as(CustomerEvent.class),为什么不在CustomerEvent上查询?只有CustomerEvent实例可以拥有CustomerEvent.customer.id = 123,或者您不需要使用&#39; as&#39;功能。

&#39;作为&#39;我们不推荐使用JPA的Treat谓词(包含在EclipseLink 2.5.1中) - 不同之处在于,treat会排除该谓词中的非customerEvent实例,而“#”;&#39;只投出谓词,因此更难以使用而且不稳定。 Treat允许您安全地使用更复杂的表达式,例如 &#34;从事件事件中选择事件(处理(事件为CustomerEvent).customer.id = 123)或event.somethingelse = someotherCondition&#34;