Spring 如何使用注解实现事务管理呢?
下文讲述Spring使用注解使用事务管理的方法分享
Error in creating record, rolling back
Exception in thread "main" java.lang.RuntimeException: simulate Error condition
...
实现思路: 使用 Annotation 需进行以下设置 1.在 Spring 容器中注册驱动 <tx:annotation-driven transaction-manager="txManager" /> 2.在需要使用事务的业务类或者方法中添加注解 @Transactional, 并配置 @Transactional 的参数 @Transactional参数如下所示: propagation:设置事务的传播行为 isolation:设置事务的隔离级别 readOnly:设置是读写事务还是只读事务 timeout:事务超时事件(单位:s)例:
- 创建 SpringDemo 项目
- 在 src 目录下创建 com.java265 包
- 导入 Spring 相关 JAR 包及 mysql-connector-java.x.x.x.jar 包
- 在 com.java265 包下创建 User、UserDao、UserDaoImpl、Beans.xml 和 MainApp
- 运行 SpringDemo 项目
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<User> 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<User> listUser() { List<User> users = this.jdbcTemplate.query("SELECT NAME,age FROM USER", new RowMapper<User>() { 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
<?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: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" /> <!--连接数据库的url --> <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
...
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。