JPA 2 (JSR 317) is a superset of JPA 1 and part of Java EE6. Added features include:
- Entities
- mixing of field and getter method annotations
- JSR 303 validation
- Relations
- unidirectional OneToMany
- use JoinTable for all relation cardinalities
- Automatic actions upon Entity changes
- CascadeType.DETACH
- orphanRemoval: delete an orphan Entity if its relation to its parent Entity is broken
- Collections
- Support for mapping collections of Basic and Embeddable types (@ElementCollection)
- Map keys and values can both be Basic, Embeddable and Entity types
- Embeddables
- Can be nested
- Can have attributes with relations
- Can inherit from a MappedSuperclass
- Ordering
- @OrderBy: determine order in which elements of List attributes are loaded
- @OrderColumn: support for preserving List order in the database using an OrderColumn
- Queries
- TypedQuery <T>
- Criteria API
- JPQL
- functions and operations in SELECT clause
- COALESCE function (returns first non null argument)
- TYPE function: get class of Entity to compare with literal
- CASE expression
- KEY, VALUE, and ENTRY keywords for map operations
- use of enums
- enum and temporal literals
- Locking
- pessimistic locking support
- lock mode arguments in EntityManager methods
- Cache API
JPA 2 is implemented in Hibernate 3.5+
JPA 2.1 (JSR 338) is part of Java EE 7. Added features include:
StoredProcedureQuery proc = em.createStoredProcedureQuery("squareRoot");
proc.registerStoredProcedureParameter("square", Double.class, ParameterMode.IN);
proc.registerStoredProcedureParameter("root", Double.class, ParameterMode.OUT);
proc.setParameter("square", 338.0);
proc.execute();
Double result = (Double)storedProcedure.getOutputParameterValue("root");
@Converter/@Convert: write custom code to convert java data to/from database data
JPQL
- selectively access entity subclasses: TREAT (relation.parentEntityAttribute AS childEntity)
- support for predefined and user defined database functions: FUNCTION(name,args...)
WHERE FUNCTION (isAllowed, theater.movie, user.age)
@Entity
@NamedEntityGraph(name="withBids", attributeNodes={@NamedAttributeNode("bids")})
public class Auction
{...}
- The Auction above has bids that are normally lazily loaded.
- Using the entity graph you can ask for a variant where the bids are eagerly loaded:
Properties prop = new Properties();
prop.put("javax.persistence.loadgraph", em.getEntityGraph("withBids"););
Auction eagerBids= em.find(Auction.class, auction_id, prop);
- In addition to declaring the graph with annotations, you can construct it at runtime with an API
- The graph can also be set as a hint to a query
JPA 2.1 is implemented in Hibernate 4.3+