What’s New in JPA

The Java Persistence API (JPA) is a fundamental component for relational database–driven Java EE applications. Although JPA 2.1 was a minor release, some of the new features that were added pack a punch, and they can vastly improve overall developer productivity.

This article covers some of the latest features in JPA 2.1, which was introduced with Java EE 7. Throughout the article, we will delve into the new features of JPA 2.1, examining examples of each in a real-world application, so that you can begin applying these new features to your Java EE applications today.

The AcmePools application we will use for the examples in this article was developed using Java EE 7 with JavaServer Faces (JSF) for the front end and using Enterprise JavaBeans (EJB) beans for working with data. The application was originally built in an article entitled “PrimeFaces in the Enterprise,” which was published on Oracle Technology Network.

Database Schema and Type Mapping

Developers face several challenges when modeling database tables with Java objects. JPA 2.1 brings various enhancements in database schema and type mapping, helping to ease the transition between a relational database and Java objects. This section covers two of the new features that help in this area: attribute conversion and schema generation.

Attribute conversion. In order to represent database tables as objects, you must map each database type to a Java type, aka type mapping. For some cases, JPA does not automatically convert from a Java type to a database type or vice versa. For instance, perhaps JPA contains a specified mapping, and an application requires something different. JPA 2.1 allows you to write an attribute converter in such cases, to specify which database type should correspond to a specified Java type.

Similar to a custom Hibernate type, attribute conversion can be applied to a basic attribute or to an element of a collection type in order to convert between a database attribute (column) type and a Java object type. For instance, in the example application, we would rather see a String value of N or Y in the database than a 0 or 1 for the representation of a Java Boolean value. We can code a converter into the application to convert a Java false value to an N and a Java true value to a Y, and then store the values in VARCHARfields. To do so, you must create a converter class, which implements the javax.persistence.AttributeConverter inter-face. This interface accepts an X and a Y value, with X being the Java type and Y being the corresponding database type.

A type converter should not be applied to Id attributes, version attributes, relationship attributes, or attributes denoted as Enumerated or Temporal, because doing so makes an application nonportable. Listing 1 demonstrates a converter for Boolean-to-String conversion.



This website uses cookies to enhance your browsing experience.