前言
spring 的 JdbcTemplate 提供了很多操作JDBC的模板方法(需要注入数据源),操作简单同时也有局限性
JdbcDaoSupport 聚合了JdbcTemplate 。通过继承JdbcDaoSupport并实现MultTableTemplate(自定义)接口,来实现对JdbcTemplate进一步包装。一种模板设计模式的思想。
继承JdbcSupport
package com.learn.frame.spring.jdbc;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
/**
* spring jdbc使用
* @author Administrator
*
*/
@Repository("jdbcCustomerDao")
public class JdbcCustomerDao extends JdbcDaoSupport implements MultTableTemplate{
@Autowired
@Qualifier("dataSource")
//Autowired按类型匹配 @Qualifier 明确确实注入哪个实现类
public void setInject(DataSource dataSource){
super.setDataSource(dataSource);
}
//MultTableTemplate接口扩展CRUD .....
}
dataSource为application.xml中配置的数据源bean对象
注入JdbcCustomerDao
package com.learn.frame.spring.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;
import com.learn.frame.spring.po.User;
import com.learn.frame.spring.service.UserService;
@Service("userService2")
public class UserServiceImpl2 implements UserService{
@Autowired //按类型自动匹配
private JdbcDaoSupport template;
@Override
public User searchUserById(int id) throws Exception {
String sql = "select * from user where id = ?";
return template.getJdbcTemplate().queryForObject(sql, new Object[]{id}, new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setCd(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setBirthday(rs.getDate("birthday"));
user.setAddress(rs.getString("address"));
return user;
}
});
}
.....
}