1. 程式人生 > >spring教程--JdbcTemplate詳解

spring教程--JdbcTemplate詳解

 Spring的JdbcTemplate

JdbcTemplate模板與DbUtils工具類比較類似.

1 Spring對持久層技術支援:

JDBC:org.springframework.jdbc.core.JdbcTemplate

Hibernate3.0:org.springframework.orm.hibernate3.HibernateTemplate

IBatis(MyBatis):org.springframework.orm.ibatis.SqlMapClientTemplate

JPA:org.springframe work.orm.jpa.JpaTemplate

2 開發JDBCTemplate入門:

第一步:引入相應jar包:

* spring-tx-3.2.0.RELEASE.jar

* spring-jdbc-3.2.0.RELEASE.jar

* mysql驅動.

第二步:建立applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- 配置Spring預設的連線池 -->
	<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql:///spring3_day02"/>
		<property name="username" value="root"/>
		<property name="password" value="123"/>
	</bean> -->
	
	<!-- 配置DBCP連線池 -->
	<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql:///spring3_day02"/>
		<property name="username" value="root"/>
		<property name="password" value="123"/>
	</bean> -->
	
	<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="location" value="classpath:jdbc.properties"></property>
	</bean> -->
	
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置c3p0連線池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}"/>
		<property name="jdbcUrl" value="${jdbc.url}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	
	<!-- 定義jdbctemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<bean id="userDao" class="com.sihai.spring3.demo2.UserDao">
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>
</beans>

第三步:編寫一個測試類:

package com.sihai.spring3.demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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("classpath:applicationContext.xml")
public class SpringTest1 {
	
	@Autowired
	@Qualifier("jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void demo2(){
		jdbcTemplate.execute("create table user (id int primary key auto_increment,name varchar(20))");
	}
	
	@Test
	public void demo1(){
		// 建立連線池:
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		// 設定引數:
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql:///spring3_day02");
		dataSource.setUsername("root");
		dataSource.setPassword("123");
		
		// 使用JDBC的模板:
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.execute("create table user (id int primary key auto_increment,name varchar(20))");
	}
}

2.1 配置連線池:

Spring預設的連線池:

<!-- 配置Spring預設的連線池 -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"/>

<property name="url" value="jdbc:mysql:///spring3_day02"/>

<property name="username" value="root"/>

<property name="password" value="123"/>

</bean>


DBCP連線池:

匯入jar包:

* com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar

* com.springsource.org.apache.commons.pool-1.5.3.jar

<!-- 配置DBCP連線池 -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"/>

<property name="url" value="jdbc:mysql:///spring3_day02"/>

<property name="username" value="root"/>

<property name="password" value="123"/>

</bean>


C3P0連線池:

匯入jar包:

* com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar

<!-- 配置c3p0連線池 -->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="com.mysql.jdbc.Driver"/>

<property name="jdbcUrl" value="jdbc:mysql:///spring3_day02"/>

<property name="user" value="root"/>

<property name="password" value="123"/>

</bean>


2.2 引數設定到屬性檔案中:

在src下建立jdbc.properties

jdbc.driver = com.mysql.jdbc.Driver

jdbc.url = jdbc:mysql:///spring3_day02

jdbc.user = root

jdbc.password = 123


需要在applicationContext.xml 中使用屬性檔案配置的內容.

 第一種寫法:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

          <property name="location" value="classpath:jdbc.properties"></property>

</bean>


 第二種寫法:

<context:property-placeholder location="classpath:jdbc.properties"/>


2.3 JdbcTemplate的CRUD的操作:

Spring框架中提供了對持久層技術支援的類:

JDBC:org.springframework.jdbc.core.support.JdbcDaoSupport

Hibernate 3.0:org.springframework.orm.hibernate3.support.HibernateDaoSupport

iBatis:org.springframework.orm.ibatis.support.SqlMapClientDaoSupport

2.3.1 編寫DAO的時候:

Public class UserDao extends JdbcDaoSupport{

}

進行CRUD的操作;

* 儲存:update(String sql,Object... args)

* 修改:update(String sql,Object... args)

* 刪除:update(String sql,Object... args)

2.3.2 查詢:

 簡單查詢:

* select count(*) from user;--- queryForInt(String sql);

* select name from user where id = ?;--- queryForObject(String sql,Class clazz,Object... args);

 複雜查詢:(返回物件,和物件集合)

* select * from user where id = ?--- queryForObjectString sql,RowMapper<T> rowMapper,Object... args);

* select * from user;--- query(String sql,RowMapper<T> rowMapper,Object... args);

package com.sihai.spring3.demo2;

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;

public class UserDao extends JdbcDaoSupport{
	
	public void add(User user){
		String sql = "insert into user values (null,?)";
		this.getJdbcTemplate().update(sql, user.getName());
	}
	
	public void update(User user){
		String sql = "update user set name = ? where id = ?";
		this.getJdbcTemplate().update(sql, user.getName(),user.getId());
	}
	
	public void delete(User user){
		String sql = "delete from user where id = ?";
		this.getJdbcTemplate().update(sql, user.getId());
	}
	
	public int findCount(){
		String sql = "select count(*) from user";
		return this.getJdbcTemplate().queryForInt(sql);
	}
	
	public String findNameById(int id){
		String sql = "select name from user where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, String.class, id);
	}
	
	public User findById(int id){
		String sql = "select * from user where id = ?";
		User user = this.getJdbcTemplate().queryForObject(sql, new UserRowMapper(), id);
		return user;
	}
	
	public List<User> findAll(){
		String sql = "select * from user";
		return this.getJdbcTemplate().query(sql, new UserRowMapper());
	}
	
	class UserRowMapper implements RowMapper<User>{
		/**
		 * rs:結果集.
		 * rowNum:行號
		 */
		public User mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setName(rs.getString("name"));
			return user;
		}
		
	}
}