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

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

二、用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笔记(4) - Spring的编程式事务和声明式事务详解

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

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

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

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

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

  7. Spring MVC 的 Java Config ( 非 XML ) 配置方式

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

  8. Spring之AOP原理、代码、使用详解(XML配置方式)

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

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

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

随机推荐

  1. .net iis excel导出问题

    碰到几个问题的解决方法 1.当我远程服务器时才可以导出excel!!关闭了远程就不行... 解决:运行mmc -32组件服务 ->DCOM Config->Microsoft Excel  ...

  2. <td>标签scope属性

    HTML <td> 标签的 scope 属性 HTML <td> 标签 实例 下面的例子把两个 th 元素标识为列的表头,把两个 td 元素标识为行的表头: <table ...

  3. 无法解析 id,或者它不是字段

    解决方法:首先,看下R文件,有没有你上面的ID.没有的话,点项目-clean . 有的话,估计你是导了android里面的那个R包了,你看看你导的包有木有 “import android.R”有的话去 ...

  4. thinkphp多表联合查询

    1.两个表查询 $userid=session('user.id'); $user = M('cuser'); $data = $user->field('projectno')->whe ...

  5. axios拦截器请求头携带token

    转—— https://github.com/superman66/vue-axios-github/blob/master/src/http.js

  6. 洛谷P1155 双栈排序(贪心)

    题意 题目链接 Sol 首先不难想到一种贪心策略:能弹则弹,优先放A 然后xjb写了写发现只有\(40\),原因是存在需要决策的情况 比如 \(A = {10}\) \(B = {8}\) 现在进来一 ...

  7. 软件项目技术点(1)——d3.interpolateZoom-在两个点之间平滑地缩放平移

    AxeSlide软件项目梳理   canvas绘图系列知识点整理 软件参考d3的知识点 我们在软件中主要用到d3.js的核心函数d3.interpolateZoom - 在两个点之间平滑地缩放平移.请 ...

  8. css3 animation运用

    animation:mymove 5s infinite; @keyframes mymove { from {left:0px;} to {left:200px;} } @-webkit-keyfr ...

  9. 23_ConcurrentLinkedQueue

    [简述] ConcurrentLinkedQueue是一个适用于高并发场景下的队列,通过无锁的方式,实现了高并发状态下的高性能,通常ConcurrentLinkedQueu性能好于BlockingQu ...

  10. Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(人人网)(下)

    Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(下) 自动使用cookie的方法,告别手动拷贝cookie http模块包含一些关于cookie的模块,通过他们我们可以自动的使用co ...