JPA 2.1 adds lot of enhancements on top of the JPA 2.0 features. Some of the notable features are custom converters, criteria update, stored procedures, DDL generation, entity groups, etc. Here I have listed all the changes and explained few of the features. I will write examples for each features in the future articles.
1. Converters
One of the common problem with storing the values to the database is converting the matching data type from Java object to the database table. If the Java type has the boolean, the corresponding database values could be either ‘0’ or ‘1’. The desired conversion could not happen automatically without the explicit handling of the conversion. JPA 2.1 introduces the new annotations @Converter, @Convert and <converter>, <convert> elements. Converter is a custom converter class implements the interface AttributeConverter and annotated with the @Converter. It defines the conversion types.
@Converter public class BooleanConverter implements AttributeConverter<Boolean, String>{ @Override public String convertToDatabaseValue(Boolean indicator) { if (indicator) { return "1"; } else { return "0"; } } @Override public Boolean convertToEntityAttribute(String indicator) { return "1".equals(indicator ); } }
2. CriteriaUpdate
CriteriaUpdate is database update query. CriteriaUpdate defines the following clauses and options.
- set(String, Object), set(Path, Object), set(Path, Expression) – Defines the update’s set clause.
- where(Expression), where(Predicate...) – Defines the update’s where clause. By default all instances of the class are updated.
3. Stored Procedures
JPA 2.1 supports the calling of stored procedures by using the StoredProcedureQuery or @NamedStoredProcedureQuery annotation.