views:

19

answers:

1

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 Customer 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?

+2  A: 

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].
Pascal Thivent