Spring + JdbcTemplate + JdbcDaoSupport examples
In Spring framework, the JdbcTemplate and JdbcDaoSupport classes are used to simplify the overall database operation processes. The last tutorial, Spring + Jdbc example will be reuse to compare the different between a project before and after JdbcTemplate support.
No JdbcTemplate
In the last example, you need to create many redundant codes (create connection , close the connection , handle the exception) in all the DAO persist methods – insert, update and delete. It’s not efficient, ugly, error prone and tedious.
private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(Customer customer){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, customer.getCustId()); ps.setString(2, customer.getName()); ps.setInt(3, customer.getAge()); ps.executeUpdate(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } }
Use JdbcTemplate
With JdbcTemplate, it will handle all the redundant codes.
private DataSource dataSource; private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(Customer customer){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new Object[] { customer.getCustId(), customer.getName(),customer.getAge() }); }
See the different?
Extends JdbcDaoSupport
By extended the JdbcDaoSupport, set the datasource and JdbcTemplate in your class is no longer required, you just need to wire the datasource into JdbcCustomerDAO. The JdbcDaoSupport will handle it, and you can get the JdbcTemplate by using a getJdbcTemplate() method.
public class JdbcCustomerDAO extends JdbcDaoSupport implements CustomerDAO { //no need to set datasource here public void insert(Customer customer){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)"; getJdbcTemplate().update(sql, new Object[] { customer.getCustId(), customer.getName(),customer.getAge() }); }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <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/mkyongjava" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> </beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
Conclusion
In Spring JDBC programming, It’s always recommend to use JdbcTemplate and JdbcDaoSupport to simplify the overall processes and make your code more reusable.
You can download this full project here – Spring-IDBC-Example.zip
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
hmmmmmmmmmmm nice usage of jdbcTemplate
well wat is your CustomerDAO code can you show it…
mostly i use samething like that in spring
com.dps.midsurvey.dataaccess.orm.MaintainQuestionair
com.dps.midsurvey.dataaccess.orm.campus
com.dps.midsurvey.dataaccess.orm.Survey
org.hibernate.dialect.SQLServerDialect
true
and in code of DAO class simply use hibernate session
SessionFactory sessionFactory = null;
Session session = null;
BasicQuestionair basicQuestionair;
/**
*
* @param sessionFactory
*/
public campusDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* @param entity
* BasicQuestionair entity to persist
* @throws RuntimeException
* when the operation fails
*/
public void createcampus(campus entity) {
LoogingHelper.log(“Try to saving BasicQuestionair instance”,
Level.INFO, null);
try {
session = getSession();
Transaction tx = session.beginTransaction();
session.save(entity);
tx.commit();
LoogingHelper.log(“save successful”, Level.INFO, null);
} catch (HibernateException re) {
session.getTransaction().rollback();
LoogingHelper.log(“save failed”, Level.SEVERE, re);
throw re;
}
}
simply use of hibernate in spring