Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Introduction to the Java Persistence API

The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications. Java Persistence consists of four areas:

  • The Java Persistence API
  • The query language
  • The Java Persistence Criteria API
  • Object/relational mapping metadata
The following topics are addressed here:
  • Entities
  • Entity Inheritance
  • Managing Entities
  • Querying Entities
  • Further Information about Persistence

Entities
An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.

The persistent state of an entity is represented through either persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.

Requirements for Entity Classes
An entity class must follow these requirements.

The class must be annotated with the javax.persistence.Entity annotation.

The class must have a public or protected, no-argument constructor. The class may have other constructors.

The class must not be declared final. No methods or persistent instance variables must be declared final.

If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.

Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.

Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.

Persistent Fields and Properties in Entity Classes
The persistent state of an entity can be accessed through either the entity’s instance variables or properties. The fields or properties must be of the following Java language types:

Java primitive types

java.lang.String

Other serializable types, including:

Wrappers of Java primitive types

java.math.BigInteger

java.math.BigDecimal

java.util.Date

java.util.Calendar

java.sql.Date

java.sql.Time

java.sql.TimeStamp

User-defined serializable types

byte[]

Byte[]

char[]

Character[]

Enumerated types

Other entities and/or collections of entities

Embeddable classes

Entities may use persistent fields, persistent properties, or a combination of both. If the mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the entity uses persistent properties.

Persistent Fields
If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance variables directly. All fields not annotated javax.persistence.Transient or not marked as Java transient will be persisted to the data store. The object/relational mapping annotations must be applied to the instance variables.

Persistent Properties
If the entity uses persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter methods that are typically named after the entity class’s instance variable names. For every persistent property property of type Type of the entity, there is a getter method getProperty and setter method setProperty. If the property is a Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity uses persistent properties and has a private instance variable called firstName, the class defines a getFirstName and setFirstName method for retrieving and setting the state of the firstName instance variable.

The method signature for single-valued persistent properties are as follows:

Type getProperty()
void setProperty(Type type)
The object/relational mapping annotations for persistent properties must be applied to the getter methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or marked transient.

What and Why JPA(Java Persistence API)?

What is JPA ? 
  • JPA is the Java Persistence API, the entity persistence model for EJB 3.0
  • Standardized persistence framework which is implemented by Hibernate (or TopLink, Cayenne, etc.)
  • JPA Annotations and persistence.xml provide vendor independent configuration
  • EntityManager provides vendor independent access to persistence
  • Replaces vendor specific query languages (HQL) with standard (JPQL)
Why JPA ?
  • JPA is the standard, and standards are good!
  • Using JPA does not tie you to Hibernate.
  • JPA gives you most of the features of plain old Hibernate, except:
  • No criteria queries in JPA 2.0. Criteria query is a neat feature of Hibernate that constructs query using Java-based combinators instead of alternate query language, getting the benefit of IntelliSense and Eclipse’s refactoring tools.
  • JPA doesn’t have Hibernate’s DeleteOrphan cascade type.                   
  • Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a collection if the parent is deleted, preventing orphaning.
  • JPA doesn’t have an equivalent to Hibernate’s ScrollableResults




Managing JPA: Spring vs EJB3

With the arrival of the first commercial Java EE 5 application server (Weblogic 10) a production quality EE option to manage JPA is available. As a matter of fact, day by day I'm more comfortable with Glassfish but unfortunately it lacks the sales punch of Bea or IBM. As an architect it's a good question to determine what are the differences between a EJB3 approach versus a pure (lightweight) Spring approach and how and where to use one or the other.

As a side note, if the deployment target will be Weblogic 10+ then reading the Pitchfork Project documentation is advisable as some nice tricks can be performed.

First of all let's describe how a SLSB EJB3 likes to manage persistence. As you can imagine the entity classes stay the same and the bean will serve as a facade. Everything is then packed in an EAR file that usually contains a WAR file (for the screens), a JAR file for the EJBs and another JAR file inside the lib directory (for common libraries) with the entities. A simple code example of the implementation class:

public abstract class AbstractCRUD implements CRUD {

   protected abstract EntityManager getEntityManager();

   public void create(Object entity) {
      getEntityManager.persist(entity);
   }

   ...
}

@Stateless
@Local(GenericCRUD.class)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class GenericCRUDImpl extends AbstractCRUD implements Serializable {

   @PersistenceContext private EntityManager em;

   public EntityManager getEntityManager() {
      return em;
   }
}

The code above is simple. All the implementation logic has been moved to an abstract class (reusable later). The EJB just indicates how it should be deployed, how to obtain the EntityManager from the context or how to mange security and transactions. It's easy to see how much EJB3 has improved the developing experience. As Spring the EJB3 specification uses annotations and dependency injection. Here's a little list with pros/cons of this EJB3 approach:
ProsCons
Extremely easy to codeForces an EAR deployment
Extensive use of annotationsDI just for container managed classes
Declarative transactions and securitySeveral business layers
Optional deployment descriptorsLooses lazy loading when accessed remotely
Local or remote deployments 
Standards based 

Spring approach is different. As always they enforce a lightweight, POJO based, solution (EJBs now are as similar to a POJO as possible). They offer three distinct possibilities (and the best of all is that they're easily intechangeable by configuration):
  • The JPATemplate: Specialy useful when upgrading from other templates (ie Hibernate). Here's an use explanation by Inteface 21 themselves. It has two downsides IMHO, it's Spring dependent (invasive) and it uses inline functions (which I tend to dislike)
  • The LocalContainerEntiyManagerFactoryBean: Or converting the Spring context in a JPA container (!). As in the first case it allows declarative transactions and it adds the capability to parse @PersistenceContext for EntityManager injection.Here's another explanation
  • Leveraging the JTA (container) EntityManager. Spring will integrate with the AS and use the containers facilities.
I will go in a little more detail with the last one as it really shines in a JEE5 environment. The first thing to achieve is making Spring aware of the JTA environment so it can fetch and inject the PersistenceContext and EntityManager. This is done at the end of the web.xml file (see the schema):

<persistence-unit-ref>
   <persistence-unit-ref-name>persistenceUnit</persistence-unit-ref-name>
   <persistence-unit-name>persistenceEJBPU</persistence-unit-name>
</persistence-unit-ref>

The EntityManager should be published in the registry by now so Spring can get a hook. Add the following to the XML configuration:

<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:comp/env/persistenceUnit"/>

<bean class="org...jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<bean id="transactionManager" class="org...jta.JtaTransactionManager">

<tx:annotation-driven/>

That's all the configuration that is need. Two steps are still missing, the first one making your controllers (or beans in general) transactional and the second inject the EM into the DAO/s. To solve the first issue the easiest way is to annotate the bean with @Transactional, Spring's magic will do the rest and the bean will join/create a JTA transaction. The second is solved by using the @PersistenceContext annotation.

public class SpringCRUDImpl extends AbstractCRUD {

   private EntityManager em;

   @PersistenceContext
   public void setEntityManager(EntityManager em) {
      this.em = em;
   }

   protected EntityManager getEntityManager() {
      return em;
   }

}

As you see it's again very easy as the actual code is the same as the EJB3, just the way to get the EntityManager varies.


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email