Spring JdbcTemplate 详解
项目清单及下载地址
http://download.csdn.net/detail/u014201191/8734055
项目源码附带讲解
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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.atguigu.spring"></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.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置 Spirng 的 JdbcTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
People.java
package com.atguigu.spring.jdbc;
public class People {
private int id;
private String name;
private int n_id;
public int getN_id() {
return n_id;
}
public void setN_id(int nId) {
n_id = nId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public People() {
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
两个测试类
package com.atguigu.spring.jdbc;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
public class JDBCTest {
private ApplicationContext ctx = null;
private JdbcTemplate jdbcTemplate;
private EmployeeDao employeeDao;
private DepartmentDao departmentDao;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
employeeDao = ctx.getBean(EmployeeDao.class);
departmentDao = ctx.getBean(DepartmentDao.class);
namedParameterJdbcTemplate = ctx
.getBean(NamedParameterJdbcTemplate.class);
}
/**
* 测试连接
*/
@Test
public void testDataSource() throws SQLException {
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}
/**
* 执行 INSERT, UPDATE, DELETE
*/
@Test
public void testUpdate() {
String sql = "UPDATE people SET name = ? WHERE id = ?";
jdbcTemplate.update(sql, "Jack", 3);
}
/**
* 执行批量更新: 批量的 INSERT, UPDATE, DELETE 最后一个参数是 Object[] 的 List 类型:
* 因为修改一条记录需要一个 Object 的数组, 那么多条不就需要多个 Object 的数组吗
*/
@Test
public void testBatchUpdate() {
String sql = "INSERT INTO people(id,name, n_id) VALUES(?,?,?)";
List<Object[]> batchArgs = new ArrayList<Object[]>();
batchArgs.add(new Object[] { 5, "aa@atguigu.com", 1 });
batchArgs.add(new Object[] { 6, "bb@atguigu.com", 2 });
batchArgs.add(new Object[] { 7, "cc@atguigu.com", 1 });
jdbcTemplate.batchUpdate(sql, batchArgs);
}
/**
* 从数据库中获取一条记录, 实际得到对应的一个对象 注意不是调用 queryForObject(String sql,
* Class<Employee> requiredType, Object... args) 方法! 而需要调用
* queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
* 1. 其中的 RowMapper 指定如何去映射结果集的行, 常用的实现类为 BeanPropertyRowMapper 2. 使用 SQL
* 中列的别名完成列名和类的属性名的映射. 例如 last_name lastName 3. 不支持级联属性. JdbcTemplate 到底是一个
* JDBC 的小工具, 而不是 ORM 框架
*/
@Test
public void testQueryForObject() {
String sql = "SELECT id,Name from people WHERE id = ?";
RowMapper<People> rowMapper = new BeanPropertyRowMapper<People>(
People.class);
People people = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(people);
}
/**
* 查到实体类的集合 注意调用的不是 queryForList 方法
*/
@Test
public void testQueryForList() {
String sql = "SELECT id, name FROM people WHERE id > ?";
RowMapper<People> rowMapper = new BeanPropertyRowMapper<People>(
People.class);
List<People> people = jdbcTemplate.query(sql, rowMapper, 5);
System.out.println(people);
}
/**
* 获取单个列的值, 或做统计查询 使用 queryForObject(String sql, Class<Long> requiredType)
*/
@Test
public void testQueryForObject2() {
String sql = "SELECT count(id) FROM people";
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
/**
* 可以为参数起名字. 1. 好处: 若有多个参数, 则不用再去对应位置, 直接对应参数名, 便于维护 2. 缺点: 较为麻烦.
*/
@Test
public void testNamedParameterJdbcTemplate() {
String sql = "INSERT INTO employees(last_name, email, dept_id) VALUES(:ln,:email,:deptid)";
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("ln", "FF");
paramMap.put("email", "ff@atguigu.com");
paramMap.put("deptid", 2);
namedParameterJdbcTemplate.update(sql, paramMap);
}
/**
* 使用具名参数时, 可以使用 update(String sql, SqlParameterSource paramSource) 方法进行更新操作
* 1. SQL 语句中的参数名和类的属性一致! 2. 使用 SqlParameterSource 的
* BeanPropertySqlParameterSource 实现类作为参数.
*/
@Test
public void testNamedParameterJdbcTemplate2() {
String sql = "INSERT INTO employees(last_name, email, dept_id) "
+ "VALUES(:lastName,:email,:dpetId)";
Employee employee = new Employee();
employee.setLastName("XYZ");
employee.setEmail("xyz@sina.com");
employee.setDpetId(3);
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(
employee);
namedParameterJdbcTemplate.update(sql, paramSource);
}
@Test
public void testDepartmentDao() {
System.out.println(departmentDao.get(1));
}
@Test
public void testEmployeeDao() {
System.out.println(employeeDao.get(1));
}
}
package test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
* 使用自主装配的方法 JdbcTemplate.query(sql, args, rowMapper)
* 而不使用前面自带的封装方法JdbcTemplate.queryForObject(String sql, RowMapper<People> rowMapper, Object... args)
*/
public class JDBCTemplet extends JdbcTemplate {
public JDBCTemplet(DataSource dts) {
super(dts);
}
public boolean updata(String sql, Object[] args) {
int a = super.update(sql, args);
if (a > 0) {
return true;
}
return false;
}
public List queryForMethod(String sql, Object[] args, final Class c) {
return super.query(sql, args, new RowMapper() {
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
int count = rs.getMetaData().getColumnCount();
Method[] mst = c.getDeclaredMethods();
try {
Object ob = c.newInstance();
for (int i = 0; i < count; i++) {
String ms = "set"
+ rs.getMetaData().getColumnName(i + 1);
for (int j = 0; j < mst.length; j++) {
//equalsIgnoreCase 没有大小写的对比;
if (mst[j].getName().equalsIgnoreCase(ms)) {
mst[j].invoke(ob, rs.getObject(i + 1));
}
}
}
return ob;
} catch (Exception e) {
return null;
}
}
});
}
public List query(String sql, Object[] args, final Class c) {
final List al = new ArrayList();
Object ob;
return super.query(sql, args, new RowMapper() {
public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
Class[] classtype = new Class[arg0.getMetaData()
.getColumnCount()];
Object[] args = new Object[arg0.getMetaData().getColumnCount()];
for (int i = 0; i < arg0.getMetaData().getColumnCount(); i++) {
args[i] = arg0.getObject(i + 1);
classtype[i] = args[i].getClass();
}
try {
Constructor cors = c.getConstructor(classtype);
Object ob = cors.newInstance(args);
al.add(ob);
return ob;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});
}
}
声明事物处理
注解方式
applicationContext.xml配置如上:
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启用事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
service.java 以及 测试:
package com.atguigu.spring.jdbc;
import javax.sql.DataSource;
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.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("peopleDao")
public class PeopleDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional
public void update() {
String sql = "UPDATE people SET name = ? WHERE id = ?";
jdbcTemplate.update(sql, "Jack9", 3);
int i =1/0;
}
}
public static void main(String[] args) {
PeopleDao peopleDao = (PeopleDao) new ClassPathXmlApplicationContext(
"applicationContext.xml").getBean("peopleDao");
System.out.println();peopleDao.update();
}
添加事务注解
1.使用 propagation 指定事务的传播行为,即当前的事务方法被另外一个事务方法调用时,如何使用事务, 默认取值为 REQUIRED,即使用调用方法的事务
REQUIRES_NEW: 事务自己的事务, 调用的事务方法的事务被挂起. 如果自身方法没有异常,数据完成持久化,不管外部是否异常
2.使用 isolation 指定事务的隔离级别, 最常用的取值为 READ_COMMITTED
3.默认情况下 Spring 的声明式事务对所有的运行时异常进行回滚. 也可以通过对应的属性进行设置. 通常情况下去默认值即可.
4.使用 readOnly 指定事务是否为只读. 表示这个事务只读取数据但不更新数据,这样可以帮助数据库引擎优化事务. 若真的事一个只读取数据库值的方法, 应设置 readOnly=true
5.使用 timeout 指定强制回滚之前事务可以占用的时间.
6.noRollbackFor 对那种异常类型不进行回滚.
@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED,
noRollbackFor={UserAccountException.class})
@Transactional(propagation=Propagation.REQUIRES_NEW,
isolation=Isolation.READ_COMMITTED,
readOnly=false,
timeout=3)
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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.atguigu.spring"></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.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 配置 Spirng 的 JdbcTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置 NamedParameterJdbcTemplate, 该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2. 配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 根据方法名指定事务的属性 -->
<tx:method name="update" propagation="REQUIRES_NEW"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 3. 配置事务切入点, 以及把事务切入点和事务属性关联起来 -->
<aop:config>
<aop:pointcut expression="execution(* com.atguigu.spring.jdbc.*.*(..))"
id="txPointCut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>