天天看點

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表:

Spring中JdbcTemplate詳解一、說在前面二、執行個體代碼如下:三、實際開發中應用方式代碼

departments表:

Spring中JdbcTemplate詳解一、說在前面二、執行個體代碼如下:三、實際開發中應用方式代碼

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 點選打開連結