Spring JdbcTemplate 详解
http://download.csdn.net/detail/u014201191/8734055
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
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 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配置如上:
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)