用Java+xml配置方式实现Spring数据事务(编程式事务)

时间:2021-11-12 06:36:24

一、用Java配置的方式

1、实体类:

Role

public class Role {
private int id;
private String roleName;
private String note; @Override
public 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;
}
}

2、接口

RoleService

用Java+xml配置方式实现Spring数据事务(编程式事务)

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 {
@Autowired
DataSource dataSource;
@Autowired
private PlatformTransactionManager transactionManager = null;
@Override
public 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;
}
}

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;
}
}

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);
}
}

用Java+xml配置方式实现Spring数据事务(编程式事务)

二、用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>

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数据事务(编程式事务)的更多相关文章

  1. 全面分析 Spring 的编程式事务管理及声明式事务管理

    开始之前 关于本教程 本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本 ...

  2. 全面分析 Spring 的编程式事务管理及声明式事务管理--转

    开始之前 关于本教程 本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本 ...

  3. spring事务管理——编程式事务、声明式事务

    本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本教程假定您已经掌握了 ...

  4. Spring笔记&lpar;4&rpar; - Spring的编程式事务和声明式事务详解

    一.背景 事务管理对于企业应用而言至关重要.它保证了用户的每一次操作都是可靠的,即便出现了异常的访问情况,也不至于破坏后台数据的完整性.就像银行的自助取款机,通常都能正常为客户服务,但是也难免遇到操作 ...

  5. Spring编程式事务管理及声明式事务管理

    本文将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. Spring 事务属性分析 事务管理 ...

  6. Spring 声明式事务与编程式事务详解

    本文转载自IBM开发者论坛:https://developer.ibm.com/zh/articles/os-cn-spring-trans 根据自己的学习理解有所调整,用于学习备查. 事务管理对于企 ...

  7. Spring MVC 的 Java Config &lpar; 非 XML &rpar; 配置方式

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: solution/pom.xml web/pom.xml web.xml WebInitializer.java ...

  8. Spring之AOP原理、代码、使用详解&lpar;XML配置方式&rpar;

    Spring 的两大核心,一是IOC,另一个是AOP,本博客从原理.AOP代码以及AOP使用三个方向来讲AOP.先给出一张AOP相关的结构图,可以放大查看. 一.Spring AOP 接口设计 1.P ...

  9. Struts2第十篇【数据校验、代码方式、XML配置方式、错误信息返回样式】

    回顾以前的数据校验 使用一个FormBean对象来封装着web端来过来的数据 维护一个Map集合保存着错误信息-对各个字段进行逻辑判断 //表单提交过来的数据全都是String类型的,birthday ...

随机推荐

  1. Neutron 理解 &lpar;9&rpar;&colon; OpenStack 是如何实现 Neutron 网络 和 Nova虚机 防火墙的 &lbrack;How Nova Implements Security Group and How Neutron Implements Virtual Firewall&rsqb;

    学习 Neutron 系列文章: (1)Neutron 所实现的虚拟化网络 (2)Neutron OpenvSwitch + VLAN 虚拟网络 (3)Neutron OpenvSwitch + GR ...

  2. sql case 用法总结

    快下班了,抽点时间总结一下sql 的 case 用法. sql 里的case的作用: 用于计算条件列表的表达式,并返回可能的结果之一.sql 的case 类型于编程语言里的 if-esle if-el ...

  3. 搭建vpn环境:centos7&plus;openvpn

    vpn的含义:virtual private network vpn的作用/使用场景:最常见的一个作用,你通过公网来访问某个局域网里的主机/服务,其实就是搭建一个隧道,用公网传递你的数据包,等数据包到 ...

  4. SQL Server 2008 R2主数据服务安装

    SQL Server 2008 R2的主数据服务(Master Data Services,简称MDS)已经放出,目前是CTP版本,微软提供了下载地址: http://www.microsoft.co ...

  5. &lbrack;置顶&rsqb; 单机版hadoop实例安装

    目标:运行单机版hadoop http://localhost:50030mapredule监控界面 http://localhost:50070HDFS监控页面 -->安装linux系统 -- ...

  6. BLE开发的各种坑

    这段时间在做低功耗蓝牙(BLE)应用的开发(并不涉及蓝牙协议栈).总体感觉 Android BLE 还是不太稳定,开发起来也是各种痛苦.这里记录一些杂项和开发中遇到的问题及其解决方法,避免大家踩坑.本 ...

  7. Flask 学习 九 用户资料

    资料信息 app/models.py class User(UserMixin,db.Model): #...... name = db.Column(db.String(64)) location ...

  8. centos升级python2&period;7

    http://meiyitianabc.blog.163.com/blog/static/10502212720133192489840/

  9. 今日头条 2018 AI Camp 5 月 26 日在线笔试编程题第二道——最小分割分数

    题目: 给 n 个正整数 a_1,…,a_n, 将 n 个数顺序排成一列后分割成 m 段,每一段的分数被记为这段内所有数的和,该次分割的分数被记为 m 段分数的最大值.问所有分割方案中分割分数的最小值 ...

  10. UI多线程调用:线程间操作无效&colon; 从不是创建控件&quot&semi;Form1&quot&semi;的线程访问它&period;

    有两种方式解决 1.在窗体构造函数中写Control.CheckForIllegalCrossThreadCalls =false;2.使用Invoke等委托函数. 问题原因是.net2.0以后拒绝多 ...