spring+jdbc+template+transaction实现
使用spring和jdbc模板事务实现
1、创建实体类:
Role
- package com.wbg.sjt.entity;
- 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、创建配置JavaConfig
- package com.wbg.sjt.config;
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.ImportResource;
- import org.springframework.jdbc.core.JdbcTemplate;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.PlatformTransactionManager;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
- import org.springframework.transaction.annotation.TransactionManagementConfigurer;
- import org.springframework.transaction.interceptor.TransactionInterceptor;
- import org.springframework.transaction.support.TransactionTemplate;
- import javax.sql.DataSource;
- import java.beans.PropertyVetoException;
- @Configuration
- @ComponentScan("com.wbg.sjt.*")
- @EnableTransactionManagement
- public class JavaConfig {
- @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;
- }
- @Bean
- public JdbcTemplate jdbcTemplate() {
- JdbcTemplate jdbcTemplate = new JdbcTemplate();
- jdbcTemplate.setDataSource(getDataSource());
- return jdbcTemplate;
- }
- @Bean
- public PlatformTransactionManager platformTransactionManager() {
- DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
- transactionManager.setDataSource(getDataSource());
- return transactionManager;
- }
- @Bean
- TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){
- return new TransactionTemplate(platformTransactionManager);
- }
- }
3、创建dao
当出错的时候,事务滚动,数据库数据不变
代码:
- package com.wbg.sjt.service;
- import com.wbg.sjt.entity.Role;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.jdbc.core.JdbcOperations;
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.stereotype.Repository;
- import org.springframework.transaction.PlatformTransactionManager;
- import org.springframework.transaction.TransactionStatus;
- import org.springframework.transaction.support.DefaultTransactionDefinition;
- import org.springframework.transaction.support.TransactionTemplate;
- import javax.sql.DataSource;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- @Repository
- public class RoleDao {
- @Autowired
- DataSource dataSource;
- @Autowired
- private PlatformTransactionManager transactionManager = null;
- @Autowired
- private TransactionTemplate transactionTemplate;
- ;
- @Autowired
- private JdbcOperations jdbcOperations;
- public Role getRole(){
- String sql = "select * from role where id = 1";
- Role role = jdbcOperations.queryForObject(
- sql,
- /*
- //方式一
- new RowMapper<Role>() {
- @Override
- public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
- return new Role(rs.getInt(1),rs.getString(2),rs.getString(3));
- }
- }*/
- //方式二:
- (rs, rowNum) -> new Role(rs.getInt(1),rs.getString(2),rs.getString(3))
- );
- return role;
- }
- public void create() {
- transactionTemplate.execute(status -> {
- //让事务出错
- String sql = "insert into role(role_name,note) values(?,?)";
- String sql2 = "insert into role(role_namess,note) values(?,?)";
- jdbcOperations.update(sql, "sql", "aa");
- jdbcOperations.update(sql2, "sql", "aa");
- return null;
- });
- }
- //0代码实现
- 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 {
- try {
- if (connection != null)
- connection.close();
- if(preparedStatement != null)
- preparedStatement.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- return list;
- }
- public List<Map<String, Object>> getToList() {
- List<Map<String, Object>> list = jdbcOperations.queryForList("select * from role");
- return list;
- }
- public Map<String, Object> getToMap() {
- String sql = "select * from role where id = ?";
- Map<String, Object> map = jdbcOperations.queryForMap(sql, 1);
- return map;
- }
- 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;
- }
- }
测试:
- package com.wbg;
- import com.wbg.sjt.config.JavaConfig;
- import com.wbg.sjt.service.RoleDao;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import java.util.Map;
- public class Main {
- public static void main(String[] args) {
- ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JavaConfig.class);
- RoleDao roleDao = applicationContext.getBean(RoleDao.class);
- System.out.println(roleDao.getRole());
- for (Map<String, Object> map : roleDao.getToList()) {
- System.out.println(map);
- }
- roleDao.create();
- System.out.println("----------------------");
- for (Map<String, Object> map : roleDao.getToList()) {
- System.out.println(map);
- }
- }
- }
demo:https://github.com/weibanggang/hibernatejpaJpaRepository.git
spring+jdbc+template+transaction实现的更多相关文章
- Unit06: Spring对JDBC的 整合支持 、 Spring+JDBC Template、Spring异常处理
Unit06: Spring对JDBC的 整合支持 . Spring+JDBC Template .Spring异常处理 1. springmvc提供的异常处理机制 我们可以将异常抛给spring框架 ...
- Java泛型在spring jdbc template中的类似应用
泛型的使用保证返回的对象类型的正确: package com.stono.gentest; import java.util.ArrayList; import java.util.List; pub ...
- Spring JDBC Framework
引自 :学习经典:Spring JDBC Framework 这里记录我对Spring JDBC框架的学习.由于Spring JDBC和我之前做的工作有很多共同之处,学习经典Framework的设计, ...
- Spring框架学习10——JDBC Template 实现数据库操作
为了简化持久化操作,Spring在JDBC API之上提供了JDBC Template组件. 1.添加依赖 添加Spring核心依赖,MySQL驱动 <!--Spring核心基础依赖--> ...
- SSM 实训笔记 -11- 使用 Spring MVC + JDBC Template 实现筛选、检索功能(maven)
SSM 实训笔记 -11- 使用 Spring MVC + JDBC Template 实现筛选.检索功能(maven) 本篇是新建的一个数据库,新建的一个完整项目. 本篇内容: (1)使用 Spri ...
- Spring的JDBC Template
Spring的JDBC Template(JDBC模板)简化JDBC API开发,使用上和Apache公司的DBUtils框架非常类似) 快速入门实例 1.创建项目后,导入Spring基础核心开发包. ...
- springboot成神之——spring boot,spring jdbc和spring transaction的使用
本文介绍spring boot,spring jdbc和spring transaction的使用 项目结构 依赖 application model层 mapper层 dao层 exception层 ...
- spring学习笔记之---JDBC Template
JDBC Template(简化持久化操作) (一)创建项目 (1)Maven配置 <dependencies> <dependency> <groupId>ju ...
- Spring之JDBC Template
时间:2017-2-5 18:16 --Spring对不同持久化技术的支持Spring为各种支持的持久化技术都提供了简单操作的模板和回调.ORM持久化技术: JDBC: org.s ...
随机推荐
- java 2018面试题-多线程汇总(含解答)
学习,内容越多.越杂的知识,越需要进行深刻的总结,这样才能记忆深刻,将知识变成自己的.这篇文章主要是对多线程的问题进行总结的,因此罗列了自己整理的多线程的问题,都是自己觉得比较经典和一些大企业面试会问 ...
- 简单工厂模式的C++、Java实现
1.简单工厂模式UML UML如下: 图1. 简单工厂模式UML 2.C++实现 类视图如下: 图2. C++实现简单工厂模式类视图 其中,SimpleFactory实现为: Product * Si ...
- 模块与包&常用模块
一.模块的使用 模块定义:一系列功能的集合体 分为三大类:1.自定义模块 2.内置模块(比如 time,os,sys) 3.第三方模块 模块的表现形式: 1.使用python编写的py文件 2.已被编 ...
- var a =10 与 a = 10的区别
学习文章------汤姆大叔-变量对象 总结笔记 变量特点: ①变量声明可以存储在变量对象中.②变量不能直接用delete删除. var a =10 与 a = 10的区别: ①a = 10只是为全局 ...
- <Android 应用 之路> 百度地图API使用(1)
简介 详情请看百度地图官方网站 http://lbsyun.baidu.com/index.php?title=androidsdk/guide/introduction 使用方式 申请密钥,针对移动 ...
- hive配置参数的说明:
hive.ddl.output.format:hive的ddl语句的输出格式,默认是text,纯文本,还有json格式,这个是0.90以后才出的新配置: hive.exec.script.wrappe ...
- Raft协议--中文论文介绍
本篇博客为著名的 RAFT 一致性算法论文的中文翻译,论文名为<In search of an Understandable Consensus Algorithm (Extended Vers ...
- Raspberry Config.txt 介绍
原文连接:http://elinux.org/RPi_config.txt Config.txt 由于树莓派并没有传统意义上的BIOS, 所以现在各种系统配置参数通常被存在"config.t ...
- linux 安装源码后的操作 ldconfig
https://blog.csdn.net/cqkxboy168/article/details/8657487 知识点: .如果使用 ldd 命令时没有找到对应的共享库文件和其具体位置,可能是两种情 ...
- 使用SDL2出现 “error LNK2019: 无法解析的外部符号 _SDL_main,该符号在函数 _main 中被引用” 时的可能错误记录
这几天在使用SDL2,之前一直都没有错,直到上午把项目搬了个地方.结果一直出现 “error LNK2019: 无法解析的外部符号 _SDL_main,该符号在函数 _main 中被引用” . 看了网 ...