Powered by Blogger.

Tuesday 18 October 2016

Java Persistence API

No comments :
The target of the Java Persistence API (JPA) is to specify a standardized, simple to use persistence model that can be used with both Java SE and Java EE.The best features and ideas flowed in, mainly from Hibernate, TopLink, and JDO. Consequently, an application that uses the interfaces of the JPA is completely independent of a special framework such as Hibernate. Its application keeps the same independence as it had before it was used with the Java Database Connectivity (JDBC) interface.
The JPA is mainly characterized by its lightness and its slimness. One of the main features of the JPA is the specification of the object relational mapping by the Java annotations directly in the persistence object.
Java Persistence Configuration: The configuration of the persistence layer occurs in a very similar way to the native Hibernate interface. The configuration is provided in the file persistence.xml in the directory META-INF. The files are bundled in persistence units.

We open a persistence-unit called HibernateJPA, which you will use later when producing an EntityManagerFactory. There you will list all classes which should be managed by the EntityManager of this factory. You have to define the same features again as in hibernate.cfg.xml, whereas the prefix hibernate has to be prefixed to the features. You discard the created file persistence.xml in the module My Entities in the directory src/META-INF.
The advantage of implementing the entities in JPA is that, due to the attribute accessor methods (not for each attribute), which should be kept persistent, access methods have to be provided (that is, get and set methods) or attributes have to be made publicly, since JPA can also read and write private attributes. In addition, a special interface does not need to be implemented or derived from a given class. Entities that are to be administered persistently by the JPA are ordinary Java objects. Only a few annotations are necessary within the class. These are essentially the identification of the class as entity with the annotation @Entity, the definition of an identity with @Id, and the declaration of the attributes. So the classes’ possibilities for expression are not limited in any way. A hierarchy of objects is managed by default by JPA as in a relation. This mapping strategy can be adjusted via annotations in order to adapt newly implemented objects to an existing database schema, for example. (See Code.) Taking the entity’s definition into consideration, let’s look at the classes Genre and Album again. You only need to insert the annotation @Entity in front of the class definition. Additionally, set the class attribute id as identity of the class by the annotation @Id. At the same time, instruct the persistence layer (in this case, Hibernate) to create a value for this attribute. The attribute genre is an ordinary attribute, so it does not need to be labeled separately. It is automatically included if it is not marked as transient. Optionally, common attributes can be marked with the annotation @Basic. Bear in mind that it is not mandatory to provide get and set methods for your attributes. In the class Genre, for example, you can omit the methods getId() and setId() if you do not need them.

There is only thing more to do in the class Album. You need to explicitly define a column name for the attribute year, since by default the column is named as the attribute itself. However, this results in an error in the case of year at the first query, because year is part of SQL. This is why you define a userspecific name with the annotation @Column. Finally, you just have to define the association of the Genre class as @ManyToOne and both your entities are ready.

To get your entities access to the annotations you have to add a dependency on the module Hibernate to the module My Entities. The Hibernate EntityManager uses the system classloader, so you do not need to add dependencies on your entities to the Hibernate module which would have led to a cyclical dependency. If that was the case, you would have had to pack the annotation in a separate module and you would get a more complicated constellation. This way, you end up with the layout and dependencies shown in Figure.

EntityManagerFactory and EntityManager:  Similar to the SessionFactory in the native Hibernate interface, an EntityManagerFactory is available with the Java Persistence API. This factory is created for a certain persistence unit. So EntityManagers, which were produced by this factory, are able to save and manage the objects in the defined database which are defined in the referring persistence unit. Normally, an EntityManagerFactory is created only once and held during the whole application runtime like the SessionFactory. You get an instance of such a factory over the bootstrap class Persistence by calling the following:

The transferred parameter HibernateJPA defines the name of one persistence unit defined in the file persistence.xml. The factory is produced for the persistence unit. The equivalent of a session—which to some extent represents a wrapper of a JDBC link—is up to the JPA in the class EntityManager. Through this manager you can access the database and save, delete, find, and query objects there. Usually, one EntityManager is used for a certain process. However, it is a bad practice if you create a new EntityManager for each query or action. Hence it is important to choose an adequate runtime of an EntityManager depending on the application context. Since there are only a few trivial database actions in this example, for simplicity’s sake let’s only use one EntityManager for the whole runtime. In practice it does not make sense to use an EntityManager for each and every action. As with the SessionFactory, it makes sense to manage the EntityManagerFactory in one module installer class (see code). This way you can also easily and properly finish having the factory shut down the application.

Saving and Loading Objects: it remains to be clarified how to access your objects over an EntityManager. Take the class DataModel, in which you implemented the interaction with the native Hibernate interface, again. You want to substitute it now with the JPA. Let’s take a look at the methods getAlbums() and getGenres(), for example. As usual, you first create a transaction in which you want to execute your query or action. With the method getTransaction() you get an instance of an EntityTransaction by the EntityManager. Start the transaction with begin() and then create a Query instance for the JPQL query SELECT a FROM Album a. This query provides all objects of the table Album. You get this result in the form of a List by the getResultList() method. Finish the transaction successfully with commit().

The Java Persistence API (JPA) is a uniform interface for object-relational bridges such as Hibernate. JPA enables transparent usage and easy compatibility between persistence systems. In this chapter you used the JPA compliant interface of Hibernate.