Spring DAO

Introduction

The Spring-DAO ( Data Access Object ) provides a consistent way to use data access frameworks like JDBC, Hibernate, JPA, JDO and other ORM frameworks.

It provides consistent exception hierarchy. This makes your application independent from underlying data access framework. You can provide consistent exception handling without worrying about specific persistent technology.

There are three key features of Spring DAO:

  1. Resource Management:

    1. The developer does not need to open or close a database connection.

    2. Spring DAO implicitly opens and closes database connections.

    3. The developer does not need to write statements for opening and closing the database connections.

  2. Exception translation:

    1. It translates all native JDBC and ORM exceptions into unchecked DataAccessException.

    2. DataAccessException exception is propagate to service layer.

    3. Programmer do not need to handle database exceptions.

    4. Service classes handles database exception.

  3. Transaction handling:

    1. Service classes handles transactions with help of Spring AOP.

    2. If unchecked exception is propagated from @Transnational method then transaction is rolled back.

Consistent exception hierarchy

There are different data access frameworks like JDBC, Hibernate, JPA, JDO etc. They have there own native Exceptions those are raised in exceptional cases. JDBC raises SQLException, Hibernate raises HibernateException, and JDO raises JDOException.

Spring provide a generic exception class hierarchy. Spring wraps all technology specific exceptions like SQLException, JDOException and HibernateException into a generic exception class DataAccessException or its subclass.

Spring-DAO translates ORM specific exceptions into DataAccessException or into its subclasses. Spring enables transparent exception translation using @Repository annotation.

Spring makes you free from handling different exceptions when you are working on different persistent frameworks.

Annotations used for configuring DAO or Repository classes

Annotation @Repository is used to make any POJO class to a DAO class. DAO class automatically open and close the connection and participate in existing transaction. In case of exception it throws object of DataAccessException class. DataAccessException is a runtime exception class.

@Repository

public class CollegeDAOJDBCImpl implements CollegeDAOInt {

private JdbcTemplate jdbcTemplate;

@Autowired

public void setDataSource(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

}

Data Connection Pool

A DAO requires access to a Data Connection Pool (aka Persistent Resource) to communicate with the database. DCP is a standard approach to optimize the database connections. Applications can not be developed without DCP.

Depending on ORM tools there are different DCPs like JDBC need access to DataSource, JPA need access to EntityManager, and Hibernate need access to SessionFactory.

DCP can auto wired using @Autowired, and @PersistenceContext annotations.

Following are DCP XML configuration for the ORM:

<!-- Database connection pool -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3306/TEST" />

<property name="username" value="root" />

<property name="password" value="" />

</bean>


<!-- Hibernate Configuration Start -->


<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="packagesToScan" value="com.sunilos.dto" />

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">

org.hibernate.dialect.MySQLDialect

</prop>

<prop key="hibernate.show_sql">true</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

</props>

</property>

</bean>

JDBC

JDBC DAO is created using @Repository annotation and injecting data-source into dao. JDBCTemplate object is created from data-source.

It is the basic thread-safe class in the JDBC core package. It handles the creation and release of resources, which helps you avoid common errors such as forgetting to close the connection.

It performs the basic tasks of the core JDBC workflow such as statement creation and execution, leaving application code to provide SQL and extract results.

@Repository

public class CollegeDAOJDBCImpl implements CollegeDAOInt {


private JdbcTemplate jdbcTemplate;

@Autowired

public void setDataSource(DataSource dataSource) {

this.jdbcTemplate = new JdbcTemplate(dataSource);

}


public long add(Account ac) {

String sql = "insert into ST_ACCOUNT (ID, TYPE, BALANCE) values (?,?,?)";

jdbcTemplate.update(sql, ac.getId(), ac.getType(), ac.getBalance());

return ac.getId();

}


public long delete(long id) {

String sql = "delete from ST_COLLEGE where id = ?";

jdbcTemplate.update(sql, ac.getId());

return ac.getId();

}



Hibernate

Hibernate has SessionFactory as Data Connection Pool (Persistent Resource). Hibernate DAO is created using @Repository annotation and injecting session factory into dao.

@Repository

public class CollegeDAOHibImpl implements CollegeDAOInt {


@Autowired

private SessionFactory sessionFactory;


public CollegeDTO findByPK(long pk) {

return sessionFactory.getCurrentSession().get(CollegeDTO.class, pk);

}


public long add(CollegeDTO dto) {

long pk = (Long) sessionFactory.getCurrentSession().save(dto);

return pk

}


//...

JPA

JPA uses @PersistenceContext annotation to inject Data Connection Pool.

@Repository

public class JPADAOImpl implements JPADAOInt {


@PersistenceContext


private EntityManager entityManager;


public CollegeDTO findByPK(long pk) {

return entityManager.find(CollegeDTO.class, pk);

}


public long add(CollegeDTO dto) {

entityManager.persist(dto);

return dto.getId();

}

// ...

}