Tuesday, May 8, 2007

JavaOne - Java Persistence API

The Java Persistence API is part of the Enterprise JavaBeans (EJB) 3.0 work. The API began as a simplified version of the EJB entity beans. However, the API evolved into plain old java objects (POJO) .... (i.e. you can call new ObjectName()). The Java Persistence API has rich modeling and query capabilities. It works inside and outside EJB containers. Key concepts of the Java Persistence API are entities, persistence units and persistence contexts.

Enties are POJO, not components. Create using the NEW keyword. They don't require interfaces and support inheritance, polymorphism, and polymorphic relationships. Queryable using the Java Persistence query language. They are managed at runtime using an EntityManager API.

One big difference is that Hibernate uses a configuration file. The Java Persistence API uses annotations.

The persistence unit is a set of managed classes that maps into a single database. It defines the scope of queries and relationships as well as contains the object/relational mapping information.

The persistence context is the runtime application context. It is a set of managed entity instances. The entities are what have been read from the database or will be written to the database. The persistence context life cycle can be managed by the application or the container (i.e. Tomcat). This context can also be scoped to handle a single transaction or multiple transactions.

Entity lifecycle operations are 1) new (creates a new entity but not yet managed), 2) persist (adds to database after commit), 3) remove (deletes from database), 4) merge (updates db) and 5) refresh (reload from database).
Note - An update is object.merge().

Example to remove an order:

@Stateless public class OrderBean implements OrderManagement {
...
@PersistenceContext EntityManager em;
...
public void deleteOrder(Long orderId){
Order order = em.find(Order.class, orderId);
em.remove(order);
order.getCustomer().getOrders().remove(order);
}
}

To summarize, following this session was difficult. Completing a few simple tutorials would be beneficial to see how it differs from Hibernate.

1 comment:

Devious Bard said...

If it uses POJO's, I'm definitely interested. I found Hibernate's configuration and "language" to be cumbersome. I hope they spent some time on making debugging problems a little easier as well.