測試單元:
package com.lcw.spring.jdbc; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class JDBCTemplate { @Test public void demo(){ DriverManagerDataSource dataSource=new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql:///spring"); dataSource.setUsername("root"); dataSource.setPassword(""); JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource); jdbcTemplate.execute("create table temp(id int primary key,name varchar(32))"); } }

很簡單吧,再來看下使用結合配置文件,完整的實現對一個類的增刪改查
首先DEMO目錄結構:

配置appliactionContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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.xsd"> <!--數據源的配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql:///spring"></property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="userDao" class="com.curd.spring.impl.UserDAOImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> </beans>
接口:IUserDAO.java
package com.curd.spring.dao; import java.util.List; import com.curd.spring.vo.User; public interface IUserDAO { public void addUser(User user); public void deleteUser(int id); public void updateUser(User user); public String searchUserName(int id); public User searchUser(int id); public List<User> findAll(); }
接口實現類:UserDAOImpl.java
按照以往Spring的依賴注入,我們需要在接口實現類中利用構造器去獲取JdbcTemplate
Spring早就幫我們想到了這點,它為我們提供了JdbcDaoSupport支持類,所有DAO繼承這個類,就會自動獲得JdbcTemplate(前提是注入DataSource)。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="userDao" class="com.curd.spring.impl.UserDAOImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean>
在我們的實現類中直接利用getJdbcTemplate就可以獲取操作對象了。
JdbcTemplate主要提供下列方法:
1、execute方法:可以用於執行任何SQL語句,一般用於執行DDL語句;
2、update方法及batchUpdate方法:update方法用於執行新增、修改、刪除等語句;batchUpdate方法用於執行批處理相關語句;
3、query方法及queryForXXX方法:用於執行查詢相關語句;
4、call方法:用於執行存儲過程、函數相關語句。
package com.curd.spring.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import com.curd.spring.dao.IUserDAO; import com.curd.spring.vo.User; public class UserDAOImpl extends JdbcDaoSupport implements IUserDAO { public void addUser(User user) { String sql = "insert into user values(?,?,?)"; this.getJdbcTemplate().update(sql, user.getId(), user.getUsername(), user.getPassword()); } public void deleteUser(int id) { String sql = "delete from user where id=?"; this.getJdbcTemplate().update(sql, id); } public void updateUser(User user) { String sql = "update user set username=?,password=? where id=?"; this.getJdbcTemplate().update(sql, user.getUsername(), user.getPassword(), user.getId()); } public String searchUserName(int id) {// 簡單查詢,按照ID查詢,返回字符串 String sql = "select username from user where id=?"; // 返回類型為String(String.class) return this.getJdbcTemplate().queryForObject(sql, String.class, id); } public List<User> findAll() {// 復雜查詢返回List集合 String sql = "select * from user"; return this.getJdbcTemplate().query(sql, new UserRowMapper()); } public User searchUser(int id) { String sql="select * from user where id=?"; return this.getJdbcTemplate().queryForObject(sql, new UserRowMapper(), id); } class UserRowMapper implements RowMapper<User> { //rs為返回結果集,以每行為單位封裝着 public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } } }
測試類:UserTest.java
package com.curd.spring.test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.curd.spring.dao.IUserDAO; import com.curd.spring.vo.User; public class UserTest { @Test//增 public void demo1(){ User user=new User(); user.setId(3); user.setUsername("admin"); user.setPassword("123456"); ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); dao.addUser(user); } @Test//改 public void demo2(){ User user=new User(); user.setId(1); user.setUsername("admin"); user.setPassword("admin"); ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); dao.updateUser(user); } @Test//刪 public void demo3(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); dao.deleteUser(3); } @Test//查(簡單查詢,返回字符串) public void demo4(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); String name=dao.searchUserName(1); System.out.println(name); } @Test//查(簡單查詢,返回對象) public void demo5(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); User user=dao.searchUser(1); System.out.println(user.getUsername()); } @Test//查(復雜查詢,返回對象集合) public void demo6(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDAO dao=(IUserDAO) applicationContext.getBean("userDao"); List<User> users=dao.findAll(); System.out.println(users.size()); } }
附:
1、Spring 為每種持久化技術 提供一個支持類,在DAO 中注入 模板工具類
(1)JDBC : org.springframework.jdbc.core.support.JdbcDaoSupport
(2)Hibernate 3.0 :org.springframework.orm.hibernate3.support.HibernateDaoSupport
(3)iBatis :org.springframework.orm.ibatis.support.SqlMapClientDaoSupport
用戶自己編寫DAO 只需要繼承 JdbcDaoSupport, 就可以注入 JdbcTemplate
2、 通過jdbcTemplate 提供 int update(String sql, Object... args) 實現增加 、修改 、刪除
3、簡單查詢,返回原始數據類型, String類型
String sql = "select count(*) from user"; // int queryForInt(String sql) String sql = "select name from user where id = ? "; // <T> T queryForObject(String sql, Class<T> requiredType, Object... args)
4、 復雜查詢
JdbcTemplate 沒有handler, 手動完成對象封裝
編寫實體類 RowMapper
class UserRowMapper implements RowMapper<User> { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { // rs 已經指向每一條數據,不需要自己調用 next,將rs指向數據 轉換 User對象 User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); return user; } }
查詢單個對象 <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
return this.getJdbcTemplate().queryForObject(sql, new UserRowMapper(),id);
查詢所有對象List集合 <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args)
return this.getJdbcTemplate().query(sql, new UserRowMapper());
以上提供的方法基本可以滿足我們的日常需要了。
