Sunday, August 9, 2015

Implementing Data access layer using Spring - different options

This scrap note explains different ways by which you can implement Data access layer using Spring. Spring provides different ways for faster development of Data access layers. 

Using Direct JDBC: 
  • Creating the Datasource
In this you can configure the Datasource by providing the JDBC url, connection factory, user credentials string and create the DAO manually 
  • Creating DAO and accessing them
You can manually create the DAO and manually define methods for inserting, deleting, retrieving and modifying the entities. 

Using JDBC Template: 
In this you can use JDBCTemplate which simplifies the work for you, you have to create the JDBCTemplate on top of the data source you have defined. JDBCTemplate can be used to query and provide simple implementations to map to objects. 

Using Spring Data Modules: 
Spring data modules are the easiest way to implement DAO. 
In this you using data modules defined for each database type such as MongoDB, Cassandra or JPA etc., 

In Spring data modules you
  • Directly define the entities. 
  • The default CRUD implementation is provided for you. 
  • In case of custom implementation for DAO, you just provide the interface definition, the implementation is provided by the container. 

Its a very fast way of developing the Repository layer. 

There are lot of Spring data modules available such as
  • Spring data MongoDB
  • Spring data Cassandra
  • Spring data JPA 
  • Spring data REDIS

You can find more information about Spring data projects in http://projects.spring.io/spring-data/

When to use what: 
You can use Spring data modules for faster development, however it is not very flexible, but supports most of the day to day activities you perform with the DB, in case you want more control - you can go for JDBC Template. If you want full control, you can go for direct JDBC implementations, but you have to spend a lot of time in the mapping etc., 

Spring and Transaction management
There are 2 ways by which you can handle transactions
  • Programmatic way
  • Declarative way

Programmatic:
In the programmatic way, you have to manage your transaction which means you have to commit or rollback using the transaction manager API. 

Declarative: 
Declarative is the preferred way by most developers. 
  • Using AOP
  • Using @Transactional annotation. 

The @Transactional attribute supports the following attributes
  • REQUIRED
  • REQUIRES_NEW
  • SUPPORTS
  • NOT_SUPPORTED
  • MANDATORY
  • NEVER
  • NESTED

Isolation attributes
  • Dirty read
  • Non repeatable read
  • Phantom read
  • Lost updates. 

Isolation levels by Spring
  • DEFAULT
  • READ_UNCOMMITTED
  • READ_COMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE


No comments:

Post a Comment