Compare and contrast the following persistence frameworks: Java Persistence API (JPA), Hibernate and Java Database Connectivity. What improvements were made in EJB3.1 and JPA2? Include topics of scalability, security, connection pools, connection factories, entity management, transactional context, query languages, ORM, JCA, JNDI, the DAO-VO design pattern and specifically persistence layer(s) on a distributed n-tier enterprise platform in your discussion.
Java Persistence API (JPA)
JPA is an abstraction above JDBC that makes it possible to be independent of SQL.
The main components of JPA are:
ORM: “Object relational mapping is a means to map objects to data stored in relational database” [1]. JPA uses annotations and/or XML descriptor files to map POJO based java objects to relational database tables.
CRUD: An entity manager manages lifecycle of JPA entities. It performs database related operations like create, retrieve, update and delete.
JPQL: Java persistence query language allows writing CRUD queries using an object oriented query language.
JTA: Java Transaction API provides transactions and locking mechanisms while accessing data concurrently.
Callbacks and listeners: They hook business logic into the life cycle of a persistent object.
Hibernate
Hibernate is an Object relationship mapping framework. Hibernate helps in mapping POJO Java classes to SQL database tables.
It has the power of significantly reducing development time.
Hibernate uses annotations and/or XML (mapping) descriptor files to map the POJO Java objects in the application domain to relational database tables.
Hibernate implements polymorphism and inheritance.
Hibernate generated SQL maintains the portability of the application to all SQL databases.
This HQL (SQL) allows create, retrieve, update and delete operations on POJO.
This framework allows development of persistent Java classes which includes object oriented features like encapsulation, inheritance, polymorphism, and collections frameworks.
Hibernate Query Language (HQL): This is an extremely powerful query language similar to SQL.
HQL is an object oriented SQL. Like SQL using tables and columns, HQL uses classes and properties. This means HQL uses object models for relational operations.
Hence, it is less verbose as compared to SQL.
JDBC
JDBC is a standard java API for accessing relational database used for persisting state.
It connects to database executes SQL statements and gets result.
JDBC can also be used in a distributed environment.
JDBC makes connection with an underlying data source using Connection Interface.
It uses following mechanisms for connections:
DriverManager – This class is the management layer of JDBC. DriverManager loads any JDBC 4.0 drivers when an application makes connection to a data source as a part of its initialization. Other JDBC drivers must be explicitly loaded.
DataSource – DataSource can be a legacy database, file system or some other source of data. It is preferred over DriveManager as it allows the underlying data source to be apparent to the application. The two important extensions of the DataSource interface are as follows:
ConnectionPoolDataSource – The connection pool names are configured in JNDI. They support caching and reusing of physical connections in a way improving application performance and scalability.
XADataSource – XAdataSource uses XAConnection objects internally. It establishes physical connection with the database using the given user name and password. The connection thus obtained can be used in distributed transaction.
Session bean and JDBC:
Java architecture implementing session beans along with JDBC, any persistence request is delegated to the JDBC tier by the session bean.
Upon request, the session bean calls JDBC layer to obtain a reference to object of type javax.sql.DataSource interface.
The DataSource type object serves acts as a resource manager factory for java.sql.Connection objects (as outlined by JDBC specification) that implement connections to a database.
Once a Connection object is retrieved, the following business logic and persistence code (reads, updates, looping resultset, transaction commit/rollback etc.) are JDBC code.
JDBC drawbacks
Java applications initially used the JDBC API to create/read/update/delete/ data into relational databases.
The JDBC API makes direct use of SQL statements to perform data persistence activities (create, read, update, and delete).
When JDBC code is implemented in Java classes, the business logic gets tightly coupled to the Java class.
The JDBC embeddable java code relies on SQL, which is not uniform across databases. Thus the code is tightly coupled to one type of database and hence difficult to migrate.
Transactional Support:
By default, JDBC drivers work in auto-commit mode, where each database SQL (read, update) is an atomic transaction.
It is very easy to disable auto-commit, execute SQL in batch mode (multiple queries/updates) and then commit or rollback the transaction.
DAO-VO
A typical DAO (Data Access object) provides an interface that describes its contract with external interfaces. This outlines a series of methods for data persistence (CRUD operations).
Generally a DAO is defined with a base interface and its methods are implemented by entity classes.
A VO (Value object) is a simple POJO to transfer the data across various tiers of Java architecture.
JDO
For every method Persistence Manager is obtained, a transaction is fetched, and operations are executed. By availing attach/detach and fetch-groups, persisted objects are made available outside the DAO layer in a seamless way.
Hibernate and JPA
JPA acts as an adapter over Hibernate. JPA provides the entire API to interact with Hibernate. In a way JPA acts as an abstraction between the java code and Hibernate. In such a architecture it is easy to replace Hibernate if need be.
JCA
Java EE Connector Architecture (JCA) is a Java-based technology solution for connecting application servers and enterprise information systems (EIS) as part of enterprise application integration (EAI) solutions. While JDBC is specifically used to connect Java EE applications to databases, JCA is a more generic architecture for connection to legacy systems.
What improvements were made in EJB3.1 and JPA2
Improvements in EJB 3.1
With EJB 3.1, there is no need to define home/local interfaces. Now EJB can be defined simple with an annotation.
Singleton beans were introduced with EJB 3.1. Singleton beans can be used for shared data at application level.
Asynchronous EJB calls are now supported with @Asynchronous method-level annotation.
Packaging and deployment can be directly done in a war file.
Session beans with a local view can be accessed without a separate local business interface.
EJB Timer Service enhancements are also included to support scheduling jobs; Stateful Session Bean timed objects and deployment-time timer creation.
Embedded container: A new embeddable API is available for executing EJB components within a Java SE environment (for unit testing, batch processing, etc.).
EJB Lite: This definition of a lightweight subset of functionalities can be provided within Java EE Profiles (such as the Java EE Web Profile).
Portable JNDI name: The syntax for looking up EJB components is now specified.
Example:
A Stateless EJB
@Stateless
public class CustomerEJB {
@PersistenceContext(unitName = “customerPU”)
private EntityManager em;
public Customer findCustById(Long id) {
return em.find(Customer.class, id);
}
public Customer createCust( Customer cust) {
em.persist(cust);
return cust;
}
}
Improvements in JPA 2.0
Collections of basic types.
Collections of embeddable.
A persistent ordering is now maintained using the @OrderColumn annotation.
Orphan removal that allows removal of child object when parent object is removed.
Pessimistic locking has also been introduced along with optimistic locking.
Foreign key mapping were introduced with JPA 2.0 for unidirectional one-to-many relationships.
Improved support for maps (java HashMaps).
Criteria query API which allows queries to be constructed in an object-oriented manner.
Improvements in JPQL syntax.
JPA 2.0 allows nesting of embeddable objects into other embeddable objects and has entity relationships.
JPA 2.0 Example:
@Entity
@NamedQuery(name = “findAllCust”, query= “select c from Customer c”)
public class Customer implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(name = “cust_name”)
private String custName;
public Customer() {
}
//….Get and set methods
@Override
public String toString(){
StringBuilder sb = new StringBuilder(100);
sb.append(“id : “);sb.append(id);sb.append(” ; “);
sb.append(“custName : “);sb.append(custName);sb.append(” ; “);
return sb.toString();
}
Cite This Work
To export a reference to this article please select a referencing style below: