Spring 如何进行编程式事务管理呢?
下文将采用示例的方式,讲述编程式事务管理的方法分享,如下所示:
commit!
commit!
姓名:java265 年龄:888
姓名:baidu 年龄:999
- 创建 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.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; public class UserDaoImpl implements UserDao { private JdbcTemplate jdbcTemplate; private UserDao userDao; private PlatformTransactionManager transactionManager; 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); } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @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(11) DEFAULT NULL,\r\n" + " PRIMARY KEY (`id`)\r\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;"); } @Override public void saveUser(User user) { TransactionDefinition def = new DefaultTransactionDefinition(); // getTransaction()用于启动事务,返回TransactionStatus实例对象 TransactionStatus status = transactionManager.getTransaction(def); try { this.jdbcTemplate.update("INSERT INTO USER(NAME,age) VALUES (?,?)", user.getName(), user.getAge()); transactionManager.commit(status); System.out.println("commit!"); } catch (Exception e) { System.out.println("Error in creating record, rolling back"); transactionManager.rollback(status); 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; } }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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 配置数据源 --> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource"> <!--数据库驱动 --> <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"> </property></property></property></property></bean> <!--配置JDBC模板 --> <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"> <!--默认必须使用数据源 --> <property name="dataSource" ref="dataSource"> </property></bean> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"> </property></bean> <bean class="com.java265.UserDaoImpl" id="userdao"> <property name="jdbcTemplate" ref="jdbcTemplate"> <property name="transactionManager" ref="transactionManager"> </property></property></bean> </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("java265", 888)); dao.saveUser(new User("baidu", 999)); List运行结果---users = dao.listUser(); for (User user : users) { System.out.println("姓名:" + user.getName() + "\t年龄:" + user.getAge()); } } }
commit!
commit!
姓名:java265 年龄:888
姓名:baidu 年龄:999
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。