Mapping Objects to Database Tables with the Java Persistence API
- Working with the Java Persistence API (JPA)
- A Simple Example Using JPA
Over the years, many frameworks have to tried to address the redundancy of repetitive databases operations such as CRUD (Create, Read, Update, and Delete) by mapping business-model classes to database tables, a process known as Object-to-Relational Mapping (ORM) to perform these actions directly.
In a Model, View, and Controller architecture, naming tables after objects makes a lot of sense. For example, a Customer object would map to a Customer table, a Product object to a Product table, and so on. Frameworks such as Hibernate perform this naming task for you. Ruby on Rails is based on this architecture, as Rails does for Ruby much like what Hibernate does for a Java application.
But using frameworks that aren't part of the J2EE specifications has some disadvantages, especially when moving the application across servlet containers. Hibernate was preferred over J2EE's heavyweight Enterprise JavaBeans specification for ORM, EJB Query Language (EJB QL), which was introduced in the EJB 2.0 specification. EJB QL wasn't easy to use because all ORM mappings had to be defined in the bean's descriptor file. It became confusing rather quickly, with the EJB 2.0 framework requiring the use of certain interfaces as well as the Java Naming and Directory Service (JNDI) for looking up objects.
Working with the Java Persistence API (JPA)
Introduced in the EJB 3.1 specification, the Java Persistence API (JPA) was based on EJB QL, but it's much lighter in weight, uses annotations, and includes a rich query language called Java Persistence Query Language (JPQL). Best of all, it's part of the J2EE 5 and 6 specifications.
To start developing with JPA, you need only the following:
- Relational database
- Domain model classes
- persistence.xml file
- Object relational mapping metadata
- Persistence provider
- Persistence application code
JPA uses Plain Old Java Objects (POJOs), making it easy to use with annotations to define certain class behaviors. Your domain model should consist of classes representing entities—lightweight persistent domain objects. You can easily annotate a POJO to behave as an entity class by using JPA. For example, you use the @Entity annotation to make the Employee class an Entity as follows:
@Entity public class Employee { }