Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Implementing Data Access Object in Java Enterprise Edition

This article introduces the design pattern Data Access Object and how we can implement it in Java EE 7. We will also see how we can use low-level APIs such as JPA, to perform CRUD operations.

Every business application interacts with a data source, which can be a relational database, object-oriented NoSQL database, an LDAP repository (Lightweight Directory Access Protocol), a file system, a web service SOAP or REST, or any other external system.

Whatever the data sources are, the application must interact with these through CRUD (create, retrieve, update, and delete) operations, thus allowing to create, retrieve, update and delete objects of the same.

There are several ways to utilize a data source, andits implementation may vary widely. For example, there are different types of SQL dialects depending on the technology, such as PostgreSQL and Oracle.

Thus, the main objective standard Data Access Object (DAO) is to encapsulate access to the data source providing an interface to the various other application layers to communicate with the data source.

The rest of the article will discuss the DAO pattern, how it is implemented in the Java EE platform and what are the other types of technologies and standards that can be used to implement it. We will see in more detail how we can use JPA API, which helps a lot in implementing the DAO pattern.

Standard Data Access Object

The DAO pattern is defined in the book "Core J2EE Patterns" as: "the standard used to abstract and encapsulate all access to the data source DAO manages the connection to the data source to obtain and store information.."

Through this abstraction and the data source encapsulation, the biggest problem that existed before its creation has been resolved and, therefore, the application is not dependent on the implementation of a specific data source. This decouples the business layer from the data source layer. Thus, if the source data changes, such as changing from an Oracle database for Postgree database, the decoupling significantly reduces any impact that could occur.

It is unusual in the corporate world to change between suppliers of the same data source, such as an Oracle database for Postgree database. This happens a lot in government agencies looking for a major update in technology and switching to other emerging or free software. However, it is more common to change, for example, a database to an XML file system, or an LDAP repository, or to a web service. In this case, the gain is found to possess a DAO pattern in a software project. Another gain with this pattern is when the project has mocks and unit tests, in which the DAO pattern significantly helps keep the structured and clean code.

Some developers also claim a gain in DAO pattern of use in the encapsulation of legacy storage systems or where it seeks to simplify access to complex implementations of data sources.

Regarding the implementation of the DAO pattern is that this encapsulates CRUD operations on an interface that must be implemented by a concrete class. This interface could be mocked and easily tested, preventing a connection to the database, for example. As is known, the use of tests with mocks is easier and recommended than the database with integration tests, as these tend to mess the database, even if the data entered is removed, and do not offer simplicity and focus in the tests. Finally, the concrete implementation of DAO uses low-level APIs, such as JPA and Hibernate to perform CRUD operations.

Implementation of the Standard DAO

The implementation of the DAO standard involves several components, such as the DAO interface and its practical implementation, the plant (or Factory) DAO and DTO (Data Transfer Object), all optional.

The DTO (Data Transfer Object) is a standard responsible for transporting the recovered or persisted data in a database through the logical layers of software. For example, to transfer a list of "User" objects with a user's information, such as your name, id and address, which were retrieved from a "Data Access Layer" to the layer "Web", the layer of "Service "would be responsible for transferring a DAO for DTO the requested data. Why the DTO is also referred to as a VO (Value Object), which is another well-known standard for Java developers.

The book "Core J2EE Patterns" DTO defines as "responsible for carrying multiple elements containing information between software layers."

Another advantage of DTO is that it reduces the number of remote requests by network applications that make calls many methods for enterprise beans. This therefore results in a significant improvement in performance.

A very common situation in use of the DTO is when not all information returned by the database is needed in another software layer. For example, in cases where it is only necessary to display some information for a user on the Web layer. Thus, DTO reduces the search to bring only the necessary information by layer, thus optimizing the transfer of information through the layers.

An API that can be important in implementing the DAO pattern is the JPA (Java Persistence API), which manages the interactions between applications and the data source, greatly reducing the time of developers who previously had to worry about these issues. JPA specifies how to access, persist and manage information between application objects and the data source. JPA does not perform the CRUD or any operation related to the information, this is just a set of interfaces and implementations necessary. However, an application server must provide support for its use. One of the novelties of the JPA in newer versions is that it now overwrites the old EJB 2.0 container-managed persistence (CMP) that was very complex and cumbersome, and rarely used. Why persistence frameworks such as Toplink and Hibernate, have been widely used to replace the CMP EJB?. With that came the specification of the JPA (released along with the EJB 3.0), in which were gathered all the qualities of the Toplink and Hibernate in a standard specification and official.

The JPA is based on the concept of an entity (former entity bean EJB 2) which is an object capable of being persisted in a database. The big advantage is that an entity in JPA is a POJO (Plain Old Java Object) that its members are recorded and mapped to a field in the data source. Therefore its implementation is quite simple and clean.

In Listing 1 is an example of an entity in JPA

Listing 1. Example of an entity in JPA

@Entity
public class Movie {

 @Id @GeneratedValue
 private Long id;

 private String title;

 private String description;

 private Float price;

 public Movie() {}


 // getters e setters da classe

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public Float getPrice() {
  return price;
 }

 public void setPrice(Float price) {
  this.price = price;
 }
}

This is a simple class with only three notes, which already makes it persistent. The class annotated with @Entity indicates that this should be treated as an entity class, and @Id and @Generated notes mark the id member as a self-generated ID field, as stated in the jargon of databases. This means that when the entity is persisted, the id field is automatically generated according to the rules of a field as self-manageable. If the data source is a database, then all the fields in this entity are persisted to the database table named Movie. It is not necessary any other annotation or implement any interface or class to indicate that the fields are persistent.

Implementing the DAO pattern in the Java EE platform

The implementation of the DAO standard Java EE platform is better assimilated by a more complete example. As an example, we can imagine that the data source is a relational database and we want to implement a movie rental store. First we start with the creation of an entity and annotate this class with appropriate annotations JPA, as shown in Listing 2.

Listing 2. Example of an entity for the film class

package com.mrbool.dataaccessobject;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

@Entity
public class Movie implements Serializable {

 private static final long serialVersionUID = -6580012241620579129 L;

 @Id @GeneratedValue
 private int id;

 private String title;

 private String description;

 private int price;

 //This annotation indicates that the attribute is not persistent
 @Transient
 private int runtimeId;


 public Movie() {}

 //getters and setters

 public int getId() {
  return this.id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getTitle() {
  return this.title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public String getDescription() {
  return this.description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public int getPrice() {
  return this.price;
 }

 public void setPrice(int price) {
  this.price = price;
 }

 public int getRuntimeId() {
  return this.runtimeId;
 }

 public void setRuntimeId(int runtimeId) {
  this.runtimeId = runtimeId;
 }

}

The class is a simple POJO with the appropriate JPA annotations. The @Entity note in class indicates that the class should be treated as an entity and should be managed by a persistence provider.

This class entity must obey some rules, such as having a constructor with no arguments, which must be public or protected, although it may also have other builders. An entity also needs a high-class level, or may not be an enum or interface and should not be a final class. Moreover, none of the persistent instance variables or its getters and setters methods may be ending. The organization must also implement the Serializable interface.

The notes of the id attribute with @Id and @GeneratedValue mark the id attribute as a primary key and self-generated. All entities must have a primary key, which can be a single attribute or a combination of attributes.

The primary key can be one of the following: any primitive type (byte, char, short, int, long), any Wrapper class of primitives (Byte, Character, Short, Integer, Long), any array of primitives or wrapper (byte [], Byte [], short [] Shot [], int, Integer [], long [], long [], etc.) or any Java type (String, BigInteger, Date).

All the entity class attributes are automatically mapped to the fields of the same name in the database Movie table, minus the annotated fields @Transient. Thus, the entity's id attribute is mapped to the table id field in the database and so it is with the other fields of the entity.

In the code in Listing 3 one DAO interface is created that should define the basic CRUD methods and some that may be useful.

Listing 3. Example of the DAO interface

package com.mrbool.dataaccessobject;

import java.util.List;

public interface MovieDAO {

 public void addMovie(Movie movie);

 public Movie getMovie(int id);

 public void removeMovie(int id);

 public void updateMovie(Movie movie);

 public List getAllMovies();

}

The Listing 4 code has the practical implementation of DAO interface displayed. In this code, we have the implementation of CRUD, which can be noted that the constructor accepts an instance of EntityManager, which is associated with a persistence context that is defined in the file persistence.xml.

The EntityManager API provides functionality to create, remove, and can create queries. It is noteworthy that any transient field is not saved or retrieved from the database.

Listing 4. Implementation of the DAO interface.

package com.mrbool.dataaccessobject;

import java.util.List;
import javax.persistence.EntityManager;

public class MovieDAOImpl implements MovieDAO {

 private EntityManager em;

 public MovieDAOImpl(EntityManager em) {
  this.em = em;
 }

 @Override
 public void addMovie(Movie movie) {
  em.persist(movie);
 }

 @Override
 public Movie getMovie(int id) {
  return getAllMovies().get(id);
 }

 @Override
 public void removeMovie(int id) {
  em.remove(getMovie(id));
 }

 @Override
 public void updateMovie(Movie movie) {
  em.merge(movie);
 }

 @Override
 public List getAllMovies() {
  return em.createQuery("SELECT movie FROM Movie movie", Movie.class).getResultList();
 }
}

In code of the Listing 5 has is an example of a DAO factory. The EntityManager is created and injected into this class and then passed as a constructor argument for criarMovieDAO method that creates the DAO object.

Listing 5. Example of implementation of a factory DAO package

package com.mrbool.dataaccessobject;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@ApplicationScoped
public class MovieDAOFactory {

 @PersistenceContext(unitName = "moviePU")
 private EntityManager em;

 @Produces
 public MovieDAO criarMovieDAO() {
  // In MovieDAOImpl we pass the created Entity Manager
  return new MovieDAOImpl(em);
 }
}

Existing in the application entities are persistence unit calls, which are defined in the persistence.xml configuration file. This file should be in the "META-INF" application.

The most significant elements of the persistence.xml file are:

  • Persistence Unit Name: where you can set a name of a persistence unit where several persistence units can be defined and selected at run time;
  • Persistence Unit Transaction: In a Java SE application, the default transaction type is RESOURCE_LOCAL, while in the Java EE environment the default transaction type is JTA. This indicates that the EntityManager participates in the transaction;
  • Provider: This element identifies the class that provides the factory to create the EntityManager instance;
  • Class: Classes that are used in the application entities should be listed in the class element;
  • Property: Additional properties may be specified, such as connection properties to the database and persistence provider properties, as well as options to delete and create new tables.

The EntityManager is associated with a persistence context that is defined in the persistence.xml file, as shown in the example in Listing 6.

Listing 6. Example of the persistence.xml file

 xmlns="http://xmlns.jcp.org/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
 
 
 org.eclipse.persistence.jpa.PersistenceProvider
 jdbc/sample
 com.mrbool.dataaccessobject.Movie

The source specific date is set in the persistence.xml file. In this example, we set the database Derby using Eclipse Link Provider. The transaction was set to JTA type because this is a Java EE implementation. Additionally, an entity class called Film has been set. In this case, you must put all com.mrbool.dataaccessobject.Movie package.

The client code is defined in the example in Listing 7. The client receives an instance of the injected DAO and use it to return all the movies.

Listing 7. Example of client code using the default structure created DAO.

package com.mrbool.dataaccessobject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.List;

@Stateless
public class Customer {
 @Inject
 MovieDAO movieDAO;

 public List getAllMovies() {
  return movieDAO.getAllMovies();
 }
}

I hope you enjoyed the article.

Bibliography

[1] Erich Gamma, Ricard Helm, Ralph Johnson, John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1994).

[2] Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra. Head First Design Patterns. O'Reilly Media, 2004.

[3] Deepak, A.; Dan, M.; John, C.; Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition). Prentice Hall, 2003.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login