Sunday, 5 January 2014

Configure Spring JDBC in five steps



Data storage and retrieving is very important for any web application. Spring is also providing the JDBC template to retrieve and save the data into database table.

We can memories the five steps to configure the spring JDBC and that can help us for interview question.

1. Set up datasource.(in application context configuration file)

  <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/myjava" />
                <property name="username" value="root" />
                <property name="password" value="password" />
   </bean> 
           
When we are working with data from database so first we need to obtain the database connection and spring does obtain it to configuring the data source.It is part of JDBC specification. It allows a container or framework to hide the data connection, connection pooling and transaction management from application code and as a developer, we directly gets the database connection.  
We can obtain the database connection either using JNDI or writing our own data source in spring framework’s JBDC layer.


2. Set bean reference for JDBC template and pass the datasource using either constructor argument or setter property.(in application context configuration file)

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource"/>
    </bean>             

org.springframework.jdbc.core.JdbcTemplate: It is key class in spring JDBC core package. It is used for core JDBC operation and reduces common errors.


3. Set bean reference for Transaction manager and pass the datasource using either constructor argument or setter property.(in application context configuration file)

 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="dataSource" />   
   </bean>  
         
Transaction Manager: A database transaction is a sequence of actions that are treats as single unit of job. This describes below four key properties known as ACID.
  1. Atomicity: A transaction is known as sequence of job known as single unit either Single Un it should be successful or unsuccessful.
  2. Consistency: This represents the consistency of the referential integrity of the database table such unique primary or foreign keys in tables.
  3.  Isolation: it should isolate the data during transaction processing on same data at a same time and it should prevent data corruption.
  4.  Durability: Once transaction has completed those data should be persist into database and cannot be erased from database due to system failure.          
4. Create a DAO interface and implementation class on your package.

   public interface TestDAO{
                int getNamesId(String passName) throws Exception;
                void saveName(String passName) throws Exception;
   }

   public class TestDAOImpl implements TestDAO{
   private JdbcTemplate jdbcTemplate;
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
     this.jdbcTemplate = jdbcTemplate;
}

 private PlatformTransactionManager transactionManager;
public void setTransactionManager(PlatformTransactionManager transactionManager) {
                  this.transactionManager = transactionManager;
}
public int getNamesId(String passName) throws Exception{
//logger entry
String sql = "SELECT name_id FROM tbl_names where name = ?";            
//logger exits
return jdbcTemplate.queryForInt(sql, new Object[]{passName});
}
public void saveName(String passName) throws Exception{
       TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);
                try{
                  String sql = "Insert Query comes here";
                  //insertion logic            
                 transactionManager.commit(status);                   
                }catch(Exception e)
                {
                   transactionManager.rollback(status);
                   throw e;                           
                }
  }           
  }
}

Spring DAO provides support for DAO (Data Access Object) to work data access technologies like JDBC, hibernate, JDO or JPA etc.             

 
5. Pass transaction manager and jdbctemplate reference to your DAOImpl class(in application context configuration file)    
                           
   <bean id="testDAO" class="com.example.dao.impl.TestDAOImpl">
                <property name="jdbcTemplate" ref="jdbcTemplate" />
                <property name="transactionManager" ref="transactionManager"/>
   </bean>

You could be clearer with above example and now you might understand to use configure the database connection using Spring JDBC.

No comments:

Post a Comment