spring JDBC事务管理
程序员文章站
2022-07-13 21:20:35
...
一直想学习怎么使用spring 的事务,在网上查了很多资料,还是不知道怎么写,大都是基于注解方式的,要么就是基于hibernate的事务,而且没有完整的例子,都是代码片段,这里我自己写了一个简单的demo,供给大家学习
1、建立一个对象(跟数据库中的表对应)
package hb.bean;
public class Book {
private int id;
private String name;
private String author;
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
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 String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
2、建立一个接口(实现对表的相关操作)
package hb.dao;
import hb.bean.Book;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface BookDAO {
//查看book表中的所有数据
public List listBook();
//向book表中插入一条数据
public void insertBook(Book book);
}
3、实现接口的操作
package hb.dao.imp;
import hb.bean.Book;
import hb.dao.BookDAO;
import hb.row.UserRowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import sun.jdbc.odbc.ee.DataSource;
@Transactional
public class BookDAOImpl extends JdbcDaoSupport implements BookDAO {
public DataSourceTransactionManager transactionManager;
public void setTransactionManager(DataSourceTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@SuppressWarnings("unchecked")
public List listBook() {
String sql = "select * from book";
//JdbcDaoSupport里面有jdbcTemplate这个对象的set方法.JdbcTemplate这个类需要配置数据源
List list = this.getJdbcTemplate().query(sql, new UserRowMapper());
return list;
}
public void insertBook(final Book book) {
final String sql = "insert into book(id,name,author,num)values(?,?,?,?)";
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
final JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
transactionTemplate.execute(new TransactionCallbackWithoutResult(){
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0) {
Object[] params = new Object[] {book.getId(), book.getName(), book.getAuthor(),book.getNum() };
//下面的语句是用来测试事务异常的情况
// new Integer("huangbiao");
jdbcTemplate.update(sql, params);
}
});
}
}
4、继承RowMapper 接口接受返回过来的结果集
package hb.row;
import hb.bean.Book;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs,int index) throws SQLException {
Book book = new Book();
System.out.println(rs.getString("name"));
book.setName(rs.getString("name"));
return book;
}
}
5、相关的配置信息
<?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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name="username" value="huangbiao"/> <property name="password" value="huangbiao"/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接释放,一直减少到msxIdle为止 --> <property name="maxIdle" value="2" /> <!-- 最小空闲值,当空闲的连接数小于阀值时,连接池就会预申请一些连接,以免洪峰到来时来不及申请 --> <property name="minIdle" value="1" /> </bean> <!-- 配置事务管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 采用@Transactional注解方式使用事务 --> <tx:annotation-driven transaction-manager="txManager"/> <bean id="bookDao" class="hb.dao.imp.BookDAOImpl" > <!-- 因为继承了JdbcDaoSupport类,该类需要注入 JdbcTemplate类对象 --> <property name="jdbcTemplate" ref="jdbcTemplate"></property> <property name="transactionManager" ref="transactionManager"></property> </bean> <!-- jdbcTemplate需要配置dataSource,因为里面有一个set方法,所以注入给它 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事务处理类,该类用于管理事务,里面有set方法注入数据源 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
6、写一个测试类(使用JUnint)
package hb.test;
import hb.bean.Book;
import hb.dao.BookDAO;
import java.util.Iterator;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class SpringTest {
private BookDAO bookDao;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@SuppressWarnings("unchecked")
@Test
//执行查询的方式
public void doQueryTest(){
try{
ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
bookDao = (BookDAO) ctx.getBean("bookDao");
List list = bookDao.listBook();
Iterator iter = list.iterator();
while(iter.hasNext()){
Book book = (Book)iter.next();
System.out.println(book.getName());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void doInsertTest(){
Book book = new Book();
book.setAuthor("huangbiao");
book.setId(90);
book.setName("hb");
book.setNum(44);
try{
ApplicationContext ctx = new FileSystemXmlApplicationContext("applicationContext.xml");
bookDao = (BookDAO) ctx.getBean("bookDao");
bookDao.insertBook(book);
}
catch (Exception e) {
e.printStackTrace();
}
}
}