- 2023-09-22 11:27:31
- 408 热度
- 0 评论
除了Spring的DIST下的包外,加入:
commons-pool.jar commons-dbcp.jar mysql-connector-java-5.1.5-bin.jar
这里使用的是mysql数据库,在test库内创建表:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
编程式事物相对声明式事物有些繁琐,但是还是有其独到的优点。编程式的事物管理可以清楚的控制事务的边界,自行控制事物开始、撤销、超时、结束等,自由控制事物的颗粒度。
借用Spring MVC 入门示例http://www.javacui.com/Framework/224.html 的代码。这里直接在Action层直接做代码示例,并使用注解进行属性注入:
首先编辑applicationContext.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> </beans>
Spring提供两种实现方式,使用PlatformTransactionManager或TransactionTemplate。
以下示例使用PlatformTransactionManager的实现类DataSourceTransactionManager来完成。
package test; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.web.bind.annotation.RequestMapping; // http://localhost:8080/spring/hello.do?user=java @org.springframework.stereotype.Controller public class HelloController{ private DataSourceTransactionManager transactionManager; private DefaultTransactionDefinition def; private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") // 使用注解注入属性 @Autowired private void setDataSource(DataSource dataSource){ jdbcTemplate = new JdbcTemplate(dataSource); transactionManager = new DataSourceTransactionManager(dataSource); // 事物定义 def = new DefaultTransactionDefinition(); // 事物传播特性 def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); // def.setReadOnly(true); // 指定后会做一些优化操作,但是必须搭配传播特性,例如:PROPAGATION_REQUIRED,PROPAGATION_REQUIRES_NEW,PROPAGATION_NESTED // def.setTimeout(1000); // 合理的超时时间,有助于系统更加有效率 } @SuppressWarnings("deprecation") @RequestMapping("/hello.do") public String hello(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString()); TransactionStatus status = transactionManager.getTransaction(def); try { jdbcTemplate.update(" update user set age=age+1; "); // 发生异常 jdbcTemplate.update(" update user set age='test'; "); transactionManager.commit(status); } catch (Exception e) { transactionManager.rollback(status); } return "hello"; } }
也可以使用TransactionTemplate来实现,它需要一个TransactionManager实例,代码如下:
package test; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.bind.annotation.RequestMapping; @org.springframework.stereotype.Controller public class HelloController{ private DataSourceTransactionManager transactionManager; private DefaultTransactionDefinition def; private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") @Autowired private void setDataSource(DataSource dataSource){ jdbcTemplate = new JdbcTemplate(dataSource); transactionManager = new DataSourceTransactionManager(dataSource); def = new DefaultTransactionDefinition(); def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); } @SuppressWarnings({ "deprecation", "unchecked" }) @RequestMapping("/hello.do") public String hello(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString()); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); Object obj = null; try { // 不需要返回值使用TransactionCallbackWithoutResultback obj = transactionTemplate.execute(new TransactionCallback(){ public Object doInTransaction(TransactionStatus arg0) { jdbcTemplate.update(" update user set age=age+1; "); // 发生异常 jdbcTemplate.update(" update user set age='test'; "); return 1; } }); } catch (Exception e) { e.printStackTrace(); } System.out.println(obj); return "hello"; } }
注意,不要再doInTransaction内做异常捕捉,否则无法控制事物。
0 评论
留下评论
热门标签
- Spring(403)
- Boot(208)
- Spring Boot(187)
- Java(82)
- Cloud(82)
- Spring Cloud(82)
- Security(60)
- Spring Security(54)
- Boot2(51)
- Spring Boot2(51)
- Redis(31)
- SQL(29)
- Mysql(25)
- IDE(24)
- Dalston(24)
- mongoDB(22)
- MVC(22)
- JDBC(22)
- IDEA(22)
- Web(21)
- CLI(20)
- Alibaba(19)
- SpringMVC(19)
- SpringBoot(17)
- Docker(17)
- Eclipse(16)
- Vue(16)
- Git(16)
- JPA(15)
- Apache(15)
- ORA(15)
- Oracle(14)
- jdk(14)
- Tomcat(14)
- Linux(14)
- HTTP(14)
- Mybatis(14)
- XML(13)
- JdbcTemplate(13)
- OAuth(13)
- Nacos(13)
- Pro(13)
- JSON(12)
- OAuth2(12)
- Data(12)
- int(11)
- Myeclipse(11)
- stream(11)
- not(10)
- Bug(10)
- maven(9)
- Map(9)
- Hystrix(9)
- ast(9)
- session(8)
- Window(8)
- Swagger(8)
- APP(8)
- Bit(8)
- API(8)
- Cache(7)
- File(7)
- mail(7)
- IntelliJ(7)
- windows(7)
- too(7)
- HTML(7)
- Github(7)
- JavaMail(7)
- Log4J(6)
- pushlet(6)
- apt(6)
- read(6)
- Freemarker(6)
- WebFlux(6)
- JSP(6)
- Bean(6)
- error(6)
- nginx(6)
- Server(6)
- ueditor(6)
- jar(6)
- UDP(6)
- ehcache(6)
- RabbitMQ(6)
- star(6)
- and(6)
- Excel(6)
- string(5)
- Syntaxhighlighter(5)
- script(5)
- Tool(5)
- Controller(5)
- swagger2(5)
- ldquo(5)
- input(5)
- Servlet(5)
- Config(5)
- Emlog(5)
- discuz(5)