Spring中JdbcTemplate詳解

Spring中JdbcTemplate詳解

一、說在前面

1、爲了使 JDBC 更加易於使用, Spring 在 JDBC API 上定義了一個抽象層, 以此建立一個 JDBC 存取框架。
2、作爲 Spring JDBC 框架的核心,JDBC 模板的設計目的是爲不同類型的 JDBC 操作提供模板方法。每個模板方法都能控制整個過程, 並允許覆蓋過程中的特定任務。通過這種方式, 可以在儘可能保留靈活性的情況下,將數據庫存取的工作量降到最低。
3、JdbcTemplate位於spring-jdbc-4.0.0.RELEASE.jar中。其全限定命名爲org.springframework.jdbc.core.JdbcTemplate。要使用JdbcTemlate還需一個spring-tx-4.0.0.RELEASE.jar。這個包包含了一下事務和異常控制。
4、JdbcTemplate主要提供以下幾類方法:
(1)execute方法:可以用於執行任何SQL語句,一般用於執行DDL語句;
(2)update方法:用於執行新增、修改、刪除等語句;
(3)batchUpdate方法:batchUpdate方法用於批處理執行新增、修改、刪除等語句相關語句;
(4)query方法及queryForXXX方法:用於執行查詢相關語句;
(5)call方法:用於執行存儲過程、函數相關語句。

二、實例代碼如下:

1、數據庫結構以及初始數據如下:
employee表:
departments表:


2、Department類
package com.at.jdbc;

public class Department {

	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}
	
}
3、Employee類
package com.at.jdbc;

public class Employee {

	private Integer id;
	private String lastName;
	private String email;
	
	private Department department;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email + ", department=" + department + "]";
	}
	
}
4、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:aop="http://www.springframework.org/schema/aop"
	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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 配置自動掃描的包 -->
	<context:component-scan base-package="com.at.jdbc"></context:component-scan>
	
	<!-- 導入資源文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 配置C3P0數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		
		<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>
	
	<!-- 配置Spring的JdbcTemplate模板類 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
</beans>
5、db.properties
jdbc.user=root
jdbc.password=111111
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring-5

jdbc.initialPoolSize=5
jdbc.maxPoolSize=10
6、JDBCTest測試類
package com.at.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class JDBCTest {
	
	private ApplicationContext ct = null;
	private JdbcTemplate jdbcTemplate;
	
	{
		ct = new ClassPathXmlApplicationContext("applicationContext.xml");
		jdbcTemplate = (JdbcTemplate) ct.getBean("jdbcTemplate");
	}
	
	/**
	 * 獲取單個列的值,或者做統計查詢
	 * 使用queryForObject(String sql, Class<Long> requiredType) 方法
	 */
	@Test
	public void testQueryForObject2(){
		String sql = "SELECT count(id) FROM employee";
		Long count = jdbcTemplate.queryForObject(sql, Long.class);
		System.out.println(count);
	}
	
	/**
	 * 查到實體類的集合
	 * 注意調用的不是queryForList方法
	 */
	@Test
	public void testQueryForList(){
		String sql = "SELECT ID,LAST_NAME lastName,EMAIL FROM employee WHERE ID > ?";
		RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
		List<Employee> employees = jdbcTemplate.query(sql, rowMapper,9);
		System.out.println(employees);
	}

	/**
	 * 從數據庫獲得一條記錄,實際得到對應的一個對象。
	 * 在這裏調用的不是 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法
	 * 而是調用 queryForObject(String sql, RowMapper<?> rowMapper, Object... args) 方法
	 * 1、其中的RowMapper 指定如何去映射結果集的行,常用的實現類是 BeanPropertyRowMapper
	 * 2、使用SQL 中的列的別名完成列名和類的屬性名的映射,例如LAST_NAME lastName
	 * 3、不支持級聯屬性,JdbcTemplate 說到底也只是一個 JDBC的小工具,而不是ORM 框架
	 */
	@Test
	public void testQueryForObject(){
		String sql = "SELECT ID,LAST_NAME lastName,EMAIL FROM employee WHERE ID = ?";
		RowMapper<?> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
		Employee employee = (Employee) jdbcTemplate.queryForObject(sql, rowMapper,1);
		System.out.println(employee);
		
	}
	
	//測試批量更新、插入、刪除
	//最後一個參數Object[]的List類型,這是因爲修改一條記錄需要Object的數組,那麼修改多條肯定需要多個Object數組
	@Test
	public void testBatchUpdate(){
		String sql = "INSERT INTO employee(LAST_NAME,EMAIL,DEPT_ID) VALUES (?,?,?)";
		
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		batchArgs.add(new Object[]{"AA","[email protected]",1});
		batchArgs.add(new Object[]{"BB","[email protected]",2});
		batchArgs.add(new Object[]{"CC","[email protected]",3});
		batchArgs.add(new Object[]{"DD","[email protected]",3});
		batchArgs.add(new Object[]{"EE","[email protected]",2});
		
		jdbcTemplate.batchUpdate(sql, batchArgs);
	}
	
	//測試插入、更新、刪除
	@Test
	public void testUpdate(){
		String sql = "UPDATE employee SET LAST_NAME = ? WHERE ID = ?";
		jdbcTemplate.update(sql,"luoyepiaoxue2014",1);
	}
	
	@Test
	public void test() throws SQLException {
		DataSource dataSource = ct.getBean(DataSource.class);
		System.out.println(dataSource.getConnection());
	}

}

三、實際開發中應用方式代碼

1、EmployeeDao類
package com.at.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public Employee get(Integer id){
		
		String sql = "SELECT ID,LAST_NAME lastName,EMAIL FROM employee WHERE ID = ?";
		RowMapper<?> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
		Employee employee = (Employee) jdbcTemplate.queryForObject(sql, rowMapper,1);
		
		return employee;
	}
}
2、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:aop="http://www.springframework.org/schema/aop"
	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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 配置自動掃描的包 -->
	<context:component-scan base-package="com.at.jdbc"></context:component-scan>
	
	<!-- 導入資源文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 配置C3P0數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		
		<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>
	
	<!-- 配置Spring的JdbcTemplate模板類 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
</beans>
3、測試代碼
		ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext.xml");
		EmployeeDao employeeDao = (EmployeeDao) ct.getBean("employeeDao");
		System.out.println(employeeDao);


By luoyepiaoxue2014
微博地址:  http://weibo.com/luoyepiaoxue2014 點擊打開鏈接







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章