开发者

Can I refer to the primary key of any entity in JPQL by the name "id", regardless of the entity's ID property name?

Hibernate allows you to just say ".id". Let's say I have:

@Entity public class Customer {
  @Id private Integer customerId;
  @Basic private String customerName;
  // getters and setters
}

And I want to get the name of a customer by ID:

SELECT cust.customerName FROM Custom开发者_Go百科er cust WHERE cust.id = :customerId

Notice I put "id" rather than "customerId", as a shortcut. Is this valid JPQL, or is it only valid in Hibernate?


The JPA specification doesn't define such a shortcut, access to state fields (including an Id property) is by name:

4.3 Abstract Schema Types and Query Domains

(...)

Informally, the abstract schema type of an entity can be characterized as follows:

  • For every persistent field or get accessor method (for a persistent property) of the entity class, there is a field (“state-field”) whose abstract schema type corresponds to that of the field or the result type of the accessor method.
  • For every persistent relationship field or get accessor method (for a persistent relationship property) of the entity class, there is a field (“association-field”) whose type is the abstract schema type of the related entity (or, if the relationship is a one-to-many or many-to-many, a collection of such).

(...)

In other words, this is Hibernate specific (see section 14.5. Referring to identifier property) so don't rely on this if you want to write JPQL.


This is what you'd get with EclipseLink for example (MyEntity doesn't have an id field):

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Error compiling the query [select e from MyEntity e where e.id = :id], line 1, column 33: unknown state or association field [id] of class [com.acme.MyEntity].
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜