用Java+xml配置方式实现Spring数据事务(编程式事务)
用Java+xml配置方式实现Spring数据事务(编程式事务)
一、用Java配置的方式
1、实体类:
Role
public class Role {private int id;private String roleName;private String note;@Overridepublic String toString() {return "Role{" +"id=" + id +", roleName='" + roleName + '\'' +", note='" + note + '\'' +'}';}public Role() {}public Role(int id, String roleName, String note) {this.id = id;this.roleName = roleName;this.note = note;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public String getNote() {return note;}public void setNote(String note) {this.note = note;} }
View Code
2、接口
RoleService
3、实现类
RoleServiceImpl
package com.wbg.springtransaction.service;import com.wbg.springtransaction.config.JavaConfig; import com.wbg.springtransaction.entity.Role; import org.apache.ibatis.session.SqlSessionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition;import javax.sql.DataSource; import javax.transaction.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;@Service public class RoleServiceImpl implements RoleService {@AutowiredDataSource dataSource;@Autowiredprivate PlatformTransactionManager transactionManager = null;@Overridepublic List<Role> listAll() {List<Role> list = new ArrayList<Role>();Connection connection = null;try {connection = dataSource.getConnection();} catch (SQLException e) {e.printStackTrace();}String sql = "select * from role";PreparedStatement preparedStatement = null;try {preparedStatement = connection.prepareStatement(sql);ResultSet resultSet = preparedStatement.executeQuery();Role role = null;while (resultSet.next()) {role = new Role(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3));list.add(role);}} catch (SQLException e) {e.printStackTrace();} finally {if (connection != null) {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}return list;}public int insert(Role role) {Connection connection = null;DefaultTransactionDefinition dtd = new DefaultTransactionDefinition();dtd.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);TransactionStatus ts = transactionManager.getTransaction(dtd);String sql = "insert into role(role_name,note) values(?,?)";PreparedStatement preparedStatement = null;try {connection = dataSource.getConnection();preparedStatement = connection.prepareStatement(sql);preparedStatement.setString(1, role.getRoleName());preparedStatement.setString(2, role.getNote());preparedStatement.executeUpdate();transactionManager.commit(ts);} catch (SQLException e) {transactionManager.rollback(ts);System.out.println("原因:" + e.getMessage());}return 0;} }
View Code
4、配置:
JavaConfig
@Configuration @ComponentScan("com.wbg.springtransaction.*") @EnableTransactionManagement public class JavaConfig implements TransactionManagementConfigurer {@Bean(name = "dataSource")public DataSource getDataSource() {ComboPooledDataSource dataSource=new ComboPooledDataSource();try {dataSource.setDriverClass("org.mariadb.jdbc.Driver");} catch (PropertyVetoException e) {e.printStackTrace();}dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics");dataSource.setUser("root");dataSource.setPassword("123456");dataSource.setMaxPoolSize(30);return dataSource;}@Override@Bean("transactionManager")public PlatformTransactionManager annotationDrivenTransactionManager() {DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();transactionManager.setDataSource(getDataSource());return transactionManager;} }
View Code
5、测试:
public static void main(String[] args) throws SQLException {ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);RoleService roleService = applicationContext.getBean(RoleService.class);roleService.insert(new Role(1,"asd","ss"));for (Role role : roleService.listAll()) {System.out.println(role);}}
View Code
二、用xml进行配置:
1、创建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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"><!--配置数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="org.mariadb.jdbc.Driver" /><property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/wbg_logistics" /><property name="user" value="root" /><property name="password" value="123456" /><property name="maxPoolSize" value="30" /><property name="minPoolSize" value="10" /><property name="autoCommitOnClose" value="false" /><property name="checkoutTimeout" value="10000" /><property name="acquireRetryAttempts" value="2" /></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean> </beans>
View Code
2、配置:
@Configuration @ComponentScan("com.wbg.springtransaction.*") @EnableTransactionManagement @ImportResource({"classpath:spring-cfg.xml"}) public class JavaConfig implements TransactionManagementConfigurer { }
3、实现类RoleServiceImpl不变
4、测试:
public static void main(String[] args) throws SQLException {ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);RoleService roleService = applicationContext.getBean(RoleService.class);roleService.insert(new Role(1,"asd","ss"));for (Role role : roleService.listAll()) {System.out.println(role);}}
用Java+xml配置方式实现Spring数据事务(编程式事务)相关推荐
- Spring中的编程式事务与声明式事务
目录 编程式事务 使用TransactionTamplate 使用TransactionManager 声明式事务 XML文件配置 java代码配置---@transactional 编程式事务 通过 ...
- Spring事务处理之 编程式事务 和 声明式事务
对事务概念还不了解的可以先看一下 MySQL事务管理(初步了解) 这篇文章 !!! Spring事务管理学习步骤: 1.掌握Spring事务属性 2.掌握Spring事务核心API 3.掌握Sprin ...
- Spring框架学习笔记07:基于XML配置方式使用Spring MVC
文章目录 一.Spring MVC概述 1.MVC架构 2.Spring MVC 3.使用Spring MVC的两种方式 二.基于XML配置与注解的方式使用Spring MVC (一)创建Spring ...
- 全面分析 Spring 的编程式事务管理及声明式事务管理(转)
摘要 Spring 的事务管理是 Spring 框架中一个比较重要的知识点,该知识点本身并不复杂,只是由于其比较灵活,导致初学者很难把握.本教程从基础知识开始,详细分析了 Spring 事务管理的使用 ...
- 全面分析 Spring 的编程式事务管理及声明式事务管理--转
开始之前 关于本教程 本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本 ...
- Spring笔记(4) - Spring的编程式事务和声明式事务详解
一.背景 事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能正常为客户服务,但是也难免遇到操作 ...
- spring中编程式事务与声明式事务
spring中使用事务有两种方式,一种是编程式,一种是声明式. 编程式事务 编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManage ...
- springboot项目中的注解 启动项目的方式 解决spring的bean.xml配置不生效 spring的基础JDBC配置
依赖 创建一个 Spring Boot 工程时,可以继承自一个 spring-boot-starter-parent ,也可以不继承 先来看 parent 的基本功能有哪些? 定义了 Java 编译版 ...
- spring boot框架学习学前掌握之重要注解(2)-通过java的配置方式进行配置spring
本节主要内容: 1:通过代码演示实现零XML配置spring 2:使用重点注解理解 声明: 本文是<凯哥陪你学系列-框架学习之spring boot框架学习>中spring boot框架学 ...
- SSM框架笔记06:初探Spring——采用XML配置方式
初探Spring--采用XML配置方式 Spring框架是一个轻量级的企业级开发的一站式解决方案.所谓解决方案就是可以基于Spring解决Java EE开发的所有问题.Spring框架主要提供了I ...
最新文章
- 树莓派出微控制器了!Raspberry Pi Pico 只需 4 美元
- 带你从源码角度分析ViewGroup中事件分发流程
- Linux内核探讨-- 第三章
- dojo Quick Start/dojo入门手册--xmlhttp dojo.xhrGet
- VC6.0蕉HOOK_timeGetTime 达到变速效果
- linux mount命令衔接,Linux mount命令详解:挂载Linux系统外的文件
- js中的日期控件My97 DatePicker
- 计算机主要是以划分发展阶段的,计算机以什么划分发展阶段
- java工具类与集合类_JAVA学习---集合和工具类
- JavaScript学习(三十一)—在输入框中如何判断输入的是一个正确的网址
- Oracle EBS 两个严重漏洞可导致企业金融记录遭篡改
- 【OpenCV新手教程之十四】OpenCV霍夫变换:霍夫线变换,霍夫圆变换合辑
- BG2RHE - 树莓派安装官网新版ArduinoIDE
- 计算机房面积设置气消条件,机房消防设计方案
- 计算机如何把表格分成两排,wps表格怎么拆分单元格,excel单元格拆分两列
- jQuery 绑定3种键盘事件 keypress(键盘键按下,功能键和中文不触发),keydown(键盘键按下,所有键都触发),keyup(键盘键松开)
- 如何使用国内代理ip?
- android9 apk自动安装功能,如何在Android7.0、8.0、9.0系统下通过Intent安装apk
- python 交易量化模型_Python期货股票量化交易,多品种组合模型之动量策略!
- 李群SE(3)即欧式变换Euclidean transformation(刚性变换Rigid Transformation)
热门文章
- 别样的唐诗宋词汇——基于Python的量化分析挖掘尝试
- Linux常用知识与命令
- php move函数,php – 在null上调用成员函数move()
- mysql的管理与优化_MySQL管理与优化(9)_MySQL
- python聊天室详细教程_Python基础教程书籍案例:在线聊天室(虚拟茶话会)【下】...
- 区块链 以太坊 solidity 如何比较2个字符串相等
- TBB concurrent_set 没有erase
- nginx 调试 输出配置文件中的变量
- FISCO BCOS Solidity 智能合约Compiler error:Stack too deep, try removing local variables 如何传递超过16个参数变量
- 算法笔记二分查找问题1