一、用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. JS的Object类的属性、方法及如何创建对象

    属性 constructor:对创建对象的函数的引用(指针).对于Object类,该指针指向原始的object()函数. prototype:对该对象的对象原型的引用.对于所有的类,它默认返回Obje ...

  2. Spring学习笔记:Spring动态组装打印机

    一.如何开发一个打印机 1.可灵活配置使用彩色魔盒或灰色魔盒 2.可灵活配置打印页面的大小 二.打印机功能的实现依赖于魔盒和纸张 三.步骤: 1.定义墨盒和纸张的接口标准 package cn.pri ...

  3. Java基础(七)常用类

    一.Math类 1.Math类介绍 Math类属于java.lang包下面,里面包含用于执行基本数学运算的方法,如初等指数,对数,平方根和三角函数,该类被final修饰. 常用字段: 1.E 表示自然 ...

  4. 嵌套Golang对象的初始化

      比如有这样一个对象: type ProductConfig struct {     Site map[string]string } 对应的初始化可以如下写: var pc ProductCon ...

  5. HttpContext.Current.Request.RawUrl是什么意思?

    原始 URL 定义为 URL 中域信息之后的部分.在 URL 字符串 http://www.contoso.com/articles/recent.aspx 中,原始 URL 为/articles/r ...

  6. child_process

    child_process const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); l ...

  7. centos install redis

    1. 下载 [logan@localhost java]$ wget http://download.redis.io/releases/redis-3.2.8.tar.gz2. 解压    [log ...

  8. 54个提高PHP程序运行效率的方法(转载)

    原文地址:http://www.jb51.net/article/69677.htm 1. 如果一个方法可静态化,就对它做静态声明.速率可提升至4倍. 2. echo 比 print 快. 3. 使用 ...

  9. Windows+linux命令大集合

    net use \\ip\ipc$ " " /user:" " 建立IPC空链接 net use \\ip\ipc$ "密码" /user: ...

  10. 理解Underscore中的节流函数

    上一篇中讲解了Underscore中的去抖函数(_.debounced),这一篇就来介绍节流函数(_.throttled). 经过上一篇文章,我相信很多人都已经了解了去抖和节流的概念.去抖,在一段连续 ...