Spring JdbcTemplate 模板工具类

    JdbcTemplate 是Spring提供简化Jdbc开发模板工具类。 使用上类似 Apache DbUtils 。其实spring对不同的持久化技术都有提供相对应的模板。本文所讲的JdbcTemplate就是对JDBC的支持。spring对ibatis提供了SqlMapClientTemplate模板。Spring对Hibernate提供了HibernateTemplate.

一:JdbcTemplate快速入门

第一步: 在项目导入jar包

Spring JdbcTemplate 模板工具类_第1张图片

Spring核心4个、日志2个、测试 1个

导入jdbctemplate需要jar包

       spring-jdbc-3.2.0.RELEASE.jar

       spring-tx-3.2.0.RELEASE.jar

导入 mysql驱动包mysql-connector-java-5.0.8-bin.jar

第二步: 编写jdbc模板程序

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class MyTest {  
    @Test
    public void jdbcTemplateTest(){
        //使用JdbcTemplate完成数据库表建立
        //1.创建数据库连接池,使用spring内置的连接池
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///flysun");
        dataSource.setUsername("root");
        dataSource.setPassword("xxxxx");
        
        //2.通过连接池构造模板对象
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
        //3.执行sql语句
        jdbcTemplate.execute("create table person (id int primary key, name varchar(20))");             
    }

}

二:使用配置文件,配置JdbcTemplate

Spring配置文件配置JdbcTemplate,给其注入数据源,其中数据源的配置有三种:
Spring JdbcTemplate 模板工具类_第2张图片

1. spring内置连接池DriverManagerDataSource

Spring JdbcTemplate 模板工具类_第3张图片

2. Apache提供dbcp连接池BasicDataSource

Spring JdbcTemplate 模板工具类_第4张图片

Spring JdbcTemplate 模板工具类_第5张图片

3.  c3p0连接池ComboPooledDataSource


Spring JdbcTemplate 模板工具类_第6张图片

 外部属性文件(properties文件)

修改properties 文件 会比 修改 xml文件 方便

将经常需要修属性参数值,配置到独立properties文件 ,在xml文件引入properties

建立db.properties文件

Spring JdbcTemplate 模板工具类_第7张图片

在spring 引入properties文件


通过 ${key} 引用properties文件属性值

Spring JdbcTemplate 模板工具类_第8张图片

因此上面的配置好之后,测试类如下:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class MyTest {  
    @Autowired
    private JdbcTemplate jdbcTemplate;//拿到配置文件中配置的JdbcTemplate bean
    @Test
    public void jdbcTemplateTest(){
        //执行sql语句
        jdbcTemplate.execute("create table person (id int primary key, name varchar(20))");             
    }

}

实际应用中,我们编写Dao层,在Dao层中注入JdbcTemplate模板,

Spring JdbcTemplate 模板工具类_第9张图片

然后我们编写的Dao直接继承JdbcDaoSupport,在配置文件中,往对应的Dao中注入dataSource即可:

public class ProductDAO extends JdbcDaoSupport {
	// DAO 继承 Support ,自动提供setXXX 注入模板方法

	// 添加
	public void save(Product product) {
		String sql = "insert into product values(null,?,?)";
		this.getJdbcTemplate().update(sql, product.getName(), product.getPrice());
	}

	// 修改
	public void update(Product product) {
		String sql = "update product set name=? , price=? where id=?";
		this.getJdbcTemplate().update(sql, product.getName(), product.getPrice(), product.getPid());
	}

	// 删除
	public void delete(Product product) {
		String sql = "delete from product where id = ?";
		this.getJdbcTemplate().update(sql, product.getPid());
	}

	// 查询某个商品 名称
	public String findNameById(int id) {
		String sql = "select name from product where id =?";
		return this.getJdbcTemplate().queryForObject(sql, String.class, id);
	}

	// 查询总商品数量
	public long findTotalCount() {
		String sql = "select count(*) from product";
		return this.getJdbcTemplate().queryForLong(sql);
	}

	// 根据id 查询商品信息
	public Product findById(int id) {
		String sql = "select * from product where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, new ProductRowMapper(), id);
	}

	// 查询所有商品
	public List findAll() {
		String sql = "select * from product";
		return this.getJdbcTemplate().query(sql, new ProductRowMapper());
	}

	/**
	 * 结果集 封装程序 (只需关注 每行数据如何封装 )
	 * 
	 * @author seawind
	 * 
	 */
	private class ProductRowMapper implements RowMapper {
		@Override
		// rs 结果集对象 、rowNum 行号
		public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
			Product product = new Product();
			product.setPid(rs.getInt("id"));
			product.setName(rs.getString("name"));
			product.setPrice(rs.getDouble("price"));
			return product;
		}
	}
}

配置文件中:

Spring JdbcTemplate 模板工具类_第10张图片


你可能感兴趣的:(Spring)