在Spring JDBC开发中,您可以使用JdbcTemplate
和JdbcDaoSupport
类来简化整个数据库操作过程。
在本教程中,我们将用上一个Spring + JDBC的Demo,以查看before(No JdbcTemplate支持)和after(With JdbcTemplate支持)示例之间的差异。
1.没有JdbcTemplate的示例
Witout JdbcTemplate,您必须在所有DAO数据库操作方法中创建许多冗余代码(创建连接,关闭连接,处理异常) - 插入,更新和删除。它只是没有效率,丑陋,容易出错和繁琐。
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) {}
}
}
}
2.使用JdbcTemplate的示例
使用JdbcTemplate,您可以在冗余代码上保存大量输入,因为JdbcTemplate会自动处理它。
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()
});
}
看到不同的?
3.使用JdbcDaoSupport的示例
通过扩展JdbcDaoSupport,不再需要在类中设置数据源和JdbcTemplate,只需要将正确的数据源注入JdbcCustomerDAO即可。您可以使用getJdbcTemplate()方法获取JdbcTemplate。
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>
注意
在Spring JDBC开发中,始终建议使用JdbcTemplate
和JdbcDaoSupport
而不是自己编写JDBC代码。
转自:http://www.mkyong.com/spring/spring-jdbctemplate-jdbcdaosupport-examples/