Java  series— good practices and recommendations: Design patterns – Part 1

 In Tech Corner

Design patterns are common solutions to problems that occur often during software development. These solutions offer elegant and effective solutions. Particularly, effective in solving different problems with object creation, resource allocation, simplifying code etc. However, the context in which they are given needs to be maintained. While the solution itself undergoes customization, according to the business logic.

Design patterns – categories:

  • creational – offer solutions for solving different problems that occur during object creation
  • structural – offer solution to instantiation problems by finding ways how we can compose the classes in larger structures
  • behavioral – offer solutions to problems that happen in the communication between separate parts of the code

1. DAO DESIGN PATTERN

The design patterns can act as guidelines during the design of the architecture. This is the case with the DAO (Data Access Object) design pattern. That is to say, software architectures usually have three layers:

  • the endpoints for the app
  • the service layer i.e. the business logic
  • the data layer

By implementing the DAO design pattern we separate the part that communicates with the database from the rest of the application.

The DAO pattern defines the CRUD (create,read,update,delete) operations for all the entities. We can completely separate the persistence layer by adding named/native queries. These will be used for the entity itself.

public interface DAO<T,E extends Serializable>{
  public T save(T object);
  public Boolean delete(T object);
  public T update(T object);
  public T find(E id);
}

The interface for the DAO defines only the operations specified in the implementation. Then, the implementation itself uses generic types with provided entity manager. The entity manager is a class that takes care of all the persistence operations in the app and can be obtained using the application context.

public abstract class GenericDAO<T,E> implements DAO<T,E>{
  @PersistenceContext  
  private EntityManager entityManager;
public T save(T object){
    return entityManager.persist(object);
  }
public T find(E id){
    return entityManager.find(T.class,id);
  }
public Boolean delete(T object){
    return entityManager.remove(object);
  }
public T update(T object){
    return entityManager.merge(object);
  }
}

The example provided requires basic understanding of Hibernate and persistence with Java. Hibernate is an ORM tool (object relational mapping). It creates tables from java code and uses HQL (hibernate query language) for query typing and execution.

@Entity
@Table(name="person")
@NamedQueries
(
 {
  @NamedQuery(name=Person.GET_PERSON_BY_AGE,query="Select * from 
  User u where u.age>:age")
 }
)
public class Person{

  public static final String GET_PERSON_BY_AGE =   
  "Person.getPersonByAge";
  @Id
  @GeneratedValue( strategy = GenerationType.IDENTITY)
  @Column(name="id",unique="true")
  public int id;
  @Column(name="name")
  public String name;
  public Person(String name){
    this.name=name;
  }
  //getters and setters...
}

The DAO class used for the entity extends the generic DAO in which we implement the basic CRUD operations. So, we only need to add the specific queries that we’will use.

public PersonDAO extends GenericDAO<Person,Integer>{
public List<Person> getPersonByAge(int age){
    Query q=entityManager.createNamedQuery(Person.GET_PERSON_BY_AGE,
    Person.class);
    q.setParameter("age",5);
    return (List<Person>)q.getResultList();
  }
}

2. PROS AND CONS OF DAO DESIGN PATTERNS

Pros:

  • First it is easy to implement
  • Moreover, it offers both logical and physical separation of the code from the business logic
  • The DAO classes can be expanded easily with cache strategies, that can be implemented in the methods;
  • If the DAO class is declared as an EJB, each method can specify the transactional attribute. This way, we can control the scope of the underlying transaction;
 

Cons:

  • First, it creates an overhead in the connection with the database, because DAO objects generally handle the whole object. This is an advantage when it comes to the save operation because the whole object is stored at once. But, the read can be an expensive operation.
  • To avoid this, we use native or named queries to retrieve smaller portions of the object.
  • DAO pattern should not be used in small apps. WHY? Because its advantages would be minor and the code will become more complex.

In the following blog post, we will tackle Abstract factory design pattern. Subscribe below and never miss a story from our Java series: “Good practices and recommendations”.

Recommended Posts
Front end developmentagile transformation

SINGULAR STORY IN YOUR INBOX

Get news about career opportunities and product updates once a month.