一、用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. SQL语句表处理

    1.create table:创建表,语法: create table 表格名 ( 列名 数据类型, 列名 数据类型, ...... ) 2.constrain:约束,关键词 NOT NULL. UN ...

  2. 修改django 后台admin用户的密码

    python manage.py shellfrom django.contrib.auth.models import User from django.contrib.auth.models im ...

  3. java设计模式--基础思想总结--抽象类与架构设计思想

    抽象类?这个东西我感觉没什么卵用啊,又不能拿来new对象,没有具体的对象的抽象类,有什么实际的意义呢?这是很多刚刚接触java抽象类语法时的第一反应(当然,包括我).确实,很多刚刚接触抽象类这个概念的 ...

  4. UNIX 5种I/O模型

    Unix 5 I/O模型 I/O操作分为两步: (1)先将数据从 存储介质 (磁盘或者网络等)拷贝到 内核缓冲区,此时称为数据准备好,可以被用户读取. (2)由用户应用程序拷贝内核缓冲区数据 到用户缓 ...

  5. C中的私有成员

    skynet_context声明在.h里 但定义在.c里面 外部使用的时候无法用ctx->handle获取私有成员,会提示解引用类型错误 必须用.h里函数获取ctx里属性.

  6. 网站大于10M的视频不能播放

    IIS配置的网站,添加了几个mp4视频,有个可以正常播放,有的却不加载不出来,提示错误: net::ERR_CONNECTION_ABORTED 网上有文章说是由于安全狗bug导致,下载安装一个补丁覆 ...

  7. PHP支持多线程吗?

    https://zhidao.baidu.com/question/2053529640037778107.html

  8. ES6的新知识点

    一.变量 原有变量: var的缺点: 1.可以重复声明 2.无法限制修改 3.没有块级作用域 新增变量: let :不能重复声明,变量-可以修改,块级作用域 const:不能重复声明,变量-不可以修改 ...

  9. Scarpy+selenium 结合使用

    首先要先在spider对象实例化时,同时实例化一个浏览器对象 # -*- coding: utf-8 -*- import scrapy from selenium import webdriver ...

  10. Codeforces Round #394 (Div. 2)

    前一半是刚刚打完比赛的时候写的……不知为啥手腕有点僵,估计是前一个小时用力过度了吧= = 前四题看着还好,后两题就有点懵逼了……现在还不知道E题的题意到底是啥…… 不管了……还没找着官方题解,贴一下自 ...