转自:
下文讲述Spring使用注解使用事务管理的方法分享
实现思路:
使用 Annotation 需进行以下设置
1.在 Spring 容器中注册驱动
2.在需要使用事务的业务类或者方法中添加注解 @Transactional,
并配置 @Transactional 的参数
@Transactional参数如下所示:
propagation:设置事务的传播行为
isolation:设置事务的隔离级别
readOnly:设置是读写事务还是只读事务
timeout:事务超时事件(单位:s)
例:
使用IDEA创建一个事务的项目
User 类
- package com.java265;
- public class User {
- private int id;
- private String name;
- private int age;
- public User() {
- }
- public User(String name, Integer age) {
- this.name = name;
- this.age = age;
- }
-
- // 省略set和get方法
- }
UserDao类
- package com.java265;
- import java.util.List;
- public interface UserDao {
- /**
- * 初始化User表
- */
- void createUserTable();
- /**
- * 保存用户
- */
- void saveUser(User user);
- /**
- * 查询用户
- */
- List
listUser(); - }
UserDaoImpl 类
- package com.java265;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
- import javax.sql.DataSource;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.transaction.annotation.Isolation;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
- public class UserDaoImpl implements UserDao {
- private JdbcTemplate jdbcTemplate;
- private UserDao userDao;
- public JdbcTemplate getJdbcTemplate() {
- return jdbcTemplate;
- }
- public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
- this.jdbcTemplate = jdbcTemplate;
- }
- public UserDao getUserDao() {
- return userDao;
- }
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- public void setDataSource(DataSource datasource) {
- this.jdbcTemplate = new JdbcTemplate(datasource);
- }
- @Override
- public void createUserTable() {
- this.jdbcTemplate.execute("CREATE TABLE `user` (\r\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\r\n"
- + " `name` varchar(50) DEFAULT NULL,\r\n" + " `age` int(4) DEFAULT NULL,\r\n"
- + " PRIMARY KEY (`id`)\r\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
- }
- @Override
- public void saveUser(User user) {
- try {
- this.jdbcTemplate.update("INSERT INTO USER(NAME,age) VALUES (?,?)", user.getName(), user.getAge());
- this.jdbcTemplate.update("INSERT INTO USER(NAME,age) VALUES (?,?)", "google", 16);
- throw new RuntimeException("simulate Error condition");
- } catch (Exception e) {
- System.out.println("Error in creating record, rolling back");
- throw e;
- }
- }
- @Override
- public List
listUser() { - List
users = this.jdbcTemplate.query("SELECT NAME,age FROM USER", new RowMapper() { - public User mapRow(ResultSet rs, int rowNum) throws SQLException {
- User user = new User();
- user.setName(rs.getString("name"));
- user.setAge(rs.getInt("age"));
- return user;
- }
- });
- return users;
- }
- }
@Transactional 注解的参数之间可以使用“,”进行分隔
Beans.xml
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
-
- <bean id="dataSource"
- class="org.springframework.jdbc.datasource.DriverManagerDataSource">
-
- <property name="driverClassName"
- value="com.mysql.jdbc.Driver" />
-
- <property name="url" value="jdbc:mysql://localhost/test" />
-
- <property name="username" value="root" />
-
- <property name="password" value="root" />
- bean>
-
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- bean>
- <bean id="jdbcTemplate"
- class="org.springframework.jdbc.core.JdbcTemplate">
- <property name="dataSource" ref="dataSource" />
- bean>
- <bean id="userdao" class="com.java265.UserDaoImpl">
- <property name="dataSource" ref="dataSource" />
- <property name="jdbcTemplate" ref="jdbcTemplate" />
- bean>
-
- <tx:annotation-driven
- transaction-manager="transactionManager" />
- beans>
MainApp 类
- package com.java265;
- import java.util.List;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class MainApp {
- public static void main(String[] args) {
- ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
- UserDao dao = (UserDao) ctx.getBean("userdao");
- dao.createUserTable();
- dao.saveUser(new User("bianchengbang", 12));
- dao.saveUser(new User("baidu", 18));
- List users = dao.listUser();
- for (User user : users) {
- System.out.println("姓名:" + user.getName() + "\t年龄:" + user.getAge());
- }
- }
- }
运行结果---
Error in creating record, rolling back
Exception in thread "main" java.lang.RuntimeException: simulate Error condition
...