数据库操作之整合Mybaties和事务讲解 5节课

1、SpringBoot2.x持久化数据方式介绍
    
     简介:介绍近几年常用的访问数据库的方式和优缺点

1、原始java访问数据库
             开发流程麻烦
             1、注册驱动/加载驱动
                 Class.forName("com.mysql.jdbc.Driver")
             2、建立连接
                 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","root");
             3、创建Statement

4、执行SQL语句

5、处理结果集

6、关闭连接,释放资源

2、apache dbutils框架
             比上一步简单点
             官网:https://commons.apache.org/proper/commons-dbutils/
         3、jpa框架
             spring-data-jpa
             jpa在复杂查询的时候性能不是很好
        
         4、Hiberante   解释:ORM:对象关系映射Object Relational Mapping
             企业大都喜欢使用hibernate
        
         5、Mybatis框架  
             互联网行业通常使用mybatis
             不提供对象和关系模型的直接映射,半ORM

2、SpringBoot2.x整合Mybatis3.x注解实战
     简介:SpringBoot2.x整合Mybatis3.x注解配置实战

1、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter

2、加入依赖(可以用 http://start.spring.io/ 下载)
                    
             <!-- 引入starter-->
                     <dependency>
                         <groupId>org.mybatis.spring.boot</groupId>
                         <artifactId>mybatis-spring-boot-starter</artifactId>
                         <version>1.3.2</version>
                         <scope>runtime</scope>               
                     </dependency>
                     
              <!-- MySQL的JDBC驱动包    -->   
                      <dependency>
                         <groupId>mysql</groupId>
                         <artifactId>mysql-connector-java</artifactId>
                         <scope>runtime</scope>
                     </dependency>
             <!-- 引入第三方数据源 -->       
                     <dependency>
                         <groupId>com.alibaba</groupId>
                         <artifactId>druid</artifactId>
                         <version>1.1.6</version>
                     </dependency>

3、加入配置文件
             #mybatis.type-aliases-package=net.xdclass.base_project.domain
             #可以自动识别
             #spring.datasource.driver-class-name =com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
             spring.datasource.username =root
             spring.datasource.password =password
             #如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
             spring.datasource.type =com.alibaba.druid.pool.DruidDataSource

加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成

4、启动类增加mapper扫描
             @MapperScan("net.xdclass.base_project.mapper")

技巧:保存对象,获取数据库自增id
              @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")

说明:keyProperty java对象的属性;keyColumn表示数据库的字段

4、开发mapper
             参考语法 http://www.mybatis.org/mybatis-3/zh/java-api.html

5、sql脚本
             CREATE TABLE `user` (
               `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
               `name` varchar(128) DEFAULT NULL COMMENT ‘名称‘,
               `phone` varchar(16) DEFAULT NULL COMMENT ‘用户手机号‘,
               `create_time` datetime DEFAULT NULL COMMENT ‘创建时间‘,
               `age` int(4) DEFAULT NULL COMMENT ‘年龄‘,
               PRIMARY KEY (`id`)
             ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

controller——存放api

domain——存放实体类

mapper/dao——访问数据库接口

service——业务层

utils——工具类

代码实例:

controller/UserController.java:

  1 package net.xdclass.base_project.controller;
  2
  3
  4 import java.util.Date;
  5
  6 import net.xdclass.base_project.domain.JsonData;
  7 import net.xdclass.base_project.domain.User;
  8 import net.xdclass.base_project.service.UserService;
  9
 10 import org.springframework.beans.factory.annotation.Autowired;
 11 import org.springframework.web.bind.annotation.GetMapping;
 12 import org.springframework.web.bind.annotation.RequestMapping;
 13 import org.springframework.web.bind.annotation.RestController;
 14
 15 @RestController
 16 @RequestMapping("/api/v1/user")
 17 public class UserController {
 18
 19
 20 	@Autowired
 21 	private UserService userService;
 22
 23
 24 	/**
 25 	 * 功能描述: user 保存接口
 26 	 * @return
 27 	 */
 28 	@GetMapping("add")
 29 	public Object add(){
 30
 31 		User user = new User();
 32 		user.setAge(11);
 33 		user.setCreateTime(new Date());
 34 		user.setName("xdclass");
 35 		user.setPhone("10010000");
 36 		int id = userService.add(user);
 37
 38        return JsonData.buildSuccess(id);
 39 	}
 40
 41 //	@Autowired
 42 //	private UserMapper userMapper;
 43 //
 44 //
 45 //
 46 //	@GetMapping("findAll")
 47 //	public Object findAll(){
 48 //
 49 //       return JsonData.buildSuccess(userMapper.getAll());
 50 //	}
 51 //
 52 //
 53 //
 54 //	@GetMapping("findById")
 55 //	public Object findById(long id){
 56 //       return JsonData.buildSuccess(userMapper.findById(id));
 57 //	}
 58 //
 59 //
 60 //	@GetMapping("del_by_id")
 61 //	public Object delById(long id){
 62 //	userMapper.delete(id);
 63 //       return JsonData.buildSuccess();
 64 //	}
 65 //
 66 //	@GetMapping("update")
 67 //	public Object update(String name,int id){
 68 //		User user = new User();
 69 //		user.setName(name);
 70 //		user.setId(id);
 71 //		userMapper.update(user);
 72 //	    return JsonData.buildSuccess();
 73 //	}
 74 //
 75
 76 //	//测试事务
 77 //	@GetMapping("transac")
 78 //	public Object transac(){
 79 //		int id = userService.addAccount();
 80 //	    return JsonData.buildSuccess(id);
 81 //	}
 82 //
 83 //
 84
 85 }
 86 

实体类User.java:

  1 package net.xdclass.base_project.domain;
  2
  3 import java.util.Date;
  4
  5 public class User {
  6
  7 	private int id;
  8
  9 	private String name;
 10
 11 	private String phone;
 12
 13 	private int age;
 14
 15 	private Date createTime;
 16
 17 	public int getId() {
 18 		return id;
 19 	}
 20
 21 	public void setId(int id) {
 22 		this.id = id;
 23 	}
 24
 25 	public String getName() {
 26 		return name;
 27 	}
 28
 29 	public void setName(String name) {
 30 		this.name = name;
 31 	}
 32
 33 	public String getPhone() {
 34 		return phone;
 35 	}
 36
 37 	public void setPhone(String phone) {
 38 		this.phone = phone;
 39 	}
 40
 41 	public int getAge() {
 42 		return age;
 43 	}
 44
 45 	public void setAge(int age) {
 46 		this.age = age;
 47 	}
 48
 49 	public Date getCreateTime() {
 50 		return createTime;
 51 	}
 52
 53 	public void setCreateTime(Date createTime) {
 54 		this.createTime = createTime;
 55 	}
 56
 57
 58
 59
 60 }
 61 

UserMapper.java:

  1 package net.xdclass.base_project.mapper;
  2
  3 import net.xdclass.base_project.domain.User;
  4
  5 import org.apache.ibatis.annotations.Insert;
  6 import org.apache.ibatis.annotations.Options;
  7
  8 public interface UserMapper {
  9
 10
 11 	//推荐使用#{}取值,不要用${},因为存在注入的风险
 12 	 @Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
 13 	 @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")   //keyProperty java对象的属性;keyColumn表示数据库的字段
 14 	 int insert(User user);
 15
 16
 17
 18
 19 //
 20 //    @Select("SELECT * FROM user")
 21 //    @Results({
 22 //        @Result(column = "create_time",property = "createTime")  //javaType = java.util.Date.class
 23 //    })
 24 //    List<User> getAll();
 25 //
 26 //
 27 //
 28 //    @Select("SELECT * FROM user WHERE id = #{id}")
 29 //    @Results({
 30 //    	 @Result(column = "create_time",property = "createTime")
 31 //    })
 32 //    User findById(Long id);
 33 //
 34 //
 35 //
 36 //    @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
 37 //    void update(User user);
 38 //
 39 //    @Delete("DELETE FROM user WHERE id =#{userId}")
 40 //    void delete(Long userId);
 41 //
 42 }

UserService.java:

  1 package net.xdclass.base_project.service;
  2
  3 import net.xdclass.base_project.domain.User;
  4
  5 public interface UserService {
  6
  7 	public int add(User user);
  8
  9
 10
 11 	//public int addAccount();
 12
 13 }
 14 

UserServiceImpl.java:

  1 package net.xdclass.base_project.service.impl;
  2
  3 import java.util.Date;
  4
  5 import net.xdclass.base_project.domain.User;
  6 import net.xdclass.base_project.mapper.UserMapper;
  7 import net.xdclass.base_project.service.UserService;
  8
  9 import org.springframework.beans.factory.annotation.Autowired;
 10 import org.springframework.stereotype.Service;
 11 import org.springframework.transaction.annotation.Transactional;
 12
 13 @Service
 14 public class UserServiceImpl implements UserService{
 15
 16 	@Autowired
 17 	private UserMapper userMapper;
 18
 19 	@Override
 20 	public int add(User user) {
 21 		userMapper.insert(user);
 22 		int id = user.getId();
 23 		return id;
 24 	}
 25
 26
 27
 28
 29
 30
 31 }
 32 

浏览器输入:http://localhost:8080/api/v1/user/add

数据库查看:

添加成功

相关资料:
         http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples

整合问题集合:
             https://my.oschina.net/hxflar1314520/blog/1800035
             https://blog.csdn.net/tingxuetage/article/details/80179772

3、SpringBoot2.x整合Mybatis3.x增删改查实操和控制台打印SQL语句
     讲解:SpringBoot2.x整合Mybatis3.x增删改查实操, 控制台打印sql语句
    
     1、控制台打印sql语句       
         #增加打印sql语句,一般用于本地开发测试
         mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

2、增加mapper代码       
         @Select("SELECT * FROM user")
         @Results({
             @Result(column = "create_time",property = "createTime")  //javaType = java.util.Date.class       
         })
         List<User> getAll();
      
         @Select("SELECT * FROM user WHERE id = #{id}")
         @Results({
              @Result(column = "create_time",property = "createTime")
         })
         User findById(Long id);

@Update("UPDATE user SET name=#{name} WHERE id =#{id}")
         void update(User user);

@Delete("DELETE FROM user WHERE id =#{userId}")
         void delete(Long userId);
     
      3、增加API

@GetMapping("find_all")
         public Object findAll(){
            return JsonData.buildSuccess(userMapper.getAll());
         }
        
         @GetMapping("find_by_Id")
         public Object findById(long id){
            return JsonData.buildSuccess(userMapper.findById(id));
         }
        
         @GetMapping("del_by_id")
         public Object delById(long id){
         userMapper.delete(id);
            return JsonData.buildSuccess();
         }
        
         @GetMapping("update")
         public Object update(String name,int id){
             User user = new User();
             user.setName(name);
             user.setId(id);
             userMapper.update(user);
             return JsonData.buildSuccess();
         }

4、事务介绍和常见的隔离级别,传播行为
    
     简介:讲解什么是数据库事务,常见的隔离级别和传播行为

1、介绍什么是事务,单机事务,分布式事务处理等

2、讲解场景的隔离级别
         Serializable: 最严格,串行处理,消耗资源大
         Repeatable Read:保证了一个事务不会修改已经由另一个事务读取但未提交(回滚)的数据
         Read Committed:大多数主流数据库的默认事务等级
         Read Uncommitted:保证了读取过程中不会读取到非法数据。

3、讲解常见的传播行为
         PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务,最常见的选择。

PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。

PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。

PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起, 两个事务之间没有关系,一个异常,一个提交,不会同时回滚

PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。

PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常

5、SpringBoot整合mybatis之事务处理实战
     简介:SpringBoot整合Mybatis之事务处理实战
     1、service逻辑引入事务 @Transantional(propagation=Propagation.REQUIRED)

2、service代码
         @Override
         @Transactional
         public int addAccount() {
             User user = new User();
             user.setAge(9);
             user.setCreateTime(new Date());
             user.setName("事务测试");
             user.setPhone("000121212");
            
             userMapper.insert(user);
             int a = 1/0;

return user.getId();
         }

原文地址:https://www.cnblogs.com/116970u/p/10258191.html

时间: 2024-07-29 03:16:30

数据库操作之整合Mybaties和事务讲解 5节课的相关文章

小D课堂【SpringBoot】数据库操作之整合Mybaties和事务讲解

========================8.数据库操作之整合Mybaties和事务讲解 5节课================================ 加入小D课堂技术交流答疑群:Q群:699347262 1.SpringBoot2.x持久化数据方式介绍 简介:介绍近几年常用的访问数据库的方式和优缺点 1.原始java访问数据库 开发流程麻烦 1.注册驱动/加载驱动 Class.forName("com.mysql.jdbc.Driver") 2.建立连接 Connec

SpringBoot整合定时任务和异步任务处理 3节课

1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类             timer:配置比较麻烦,时间延后问题             timertask:不推荐 2.Quartz框架             配置更简单             xml或者注解 3.SpringBoot使用注解方式开启定时任务             1)启动类里面 @Ena

十三、EnterpriseFrameWork框架核心类库之数据库操作(多数据库事务处理)

本章介绍框架中封装的数据库操作的一些功能,在实现的过程中费了不少心思,针对不同数据库的操作(SQLServer.Oracle.DB2)这方面还是比较简单的,用工厂模式就能很好解决,反而是在多数据库同时操作方面走了不少弯路:现在从以下几个方面进行说明: 一.不同数据库操作 此处用到了工厂模式来实现不同数据库操作,看下图 AbstractDatabase是一个抽象类,定义了所有对数据库的操作抽象方法,包括执行一个SQL语句.执行存储过程.事务操作等 [Serializable] public abs

(二)Redis 笔记——发布&amp;订阅、事务、数据库操作

1. Redis 发布订阅 1.1 概述 Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. Redis 客户端可以订阅任意数量的频道. 下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 . client5 和 client1 之间的关系: 当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端: 1.2 步骤: 1.2.1.  创建了订阅频

DJango周总结二:模型层,单表,多表操作,连表操作,数据库操作,事务

django周复习二 1,模型层:  1单表操作:   13个必会操作总结    返回QuerySet对象的方法有    all()    filter()    exclude()    order_by()    reverse()    distinct()    特殊的QuerySet    values()       返回一个可迭代的字典序列    values_list() 返回一个可迭代的元祖序列    返回具体对象的    get()    first()    last() 

Spring学习4_整合Hibernate进行数据库操作

很多项目中后端通过Spring+hibernate进行数据库操作,这里通过一个简单Demo来模拟其原型. 代码结构 1.Spring配置如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSche

Spring整合hibernate4:事务管理

Spring和Hibernate整合后,通过Hibernate API进行数据库操作时发现每次都要opensession,close,beginTransaction,commit,这些都是重复的工作,我们可以把事务管理部分交给spring框架完成. 配置事务(xml方式) 使用spring管理事务后在dao中不再需要调用beginTransaction和commit,也不需要调用session.close(),使用API  sessionFactory.getCurrentSession()来

C# .NET数据库操作

C# .NET更智能的数据库操作的封装完整版(重构) 前述: 第一次发表文章,不过是对数据库简单的封装,主要是阐述下思路.那么在上篇文章,在大家的指导下和提出意见,并自己对代码进行了思考.在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请大家往下看.不过在项目中没有很多注释.笔者除了课余学习时候,大部分时间在完成学校的功课,没有许多时间,所以也就偷下懒,请大家体谅. 这次框架分为几个部分:拼接数据库语句.数据库执行.数据库连接控制.异常类.用户使用的DbHelper.等下我回用文字

Qt 学习:数据库操作

Qt 提供了 QtSql 模块来提供平台独立的基于 SQL 的数据库操作.这里我们所说的“平台独立”,既包括操作系统平台,有包括各个数据库平台.另外,我们强调了“基于 SQL”,因为 NoSQL 数据库至今没有一个通用查询方法,所以不可能提供一种通用的 NoSQL 数据库的操作.Qt 的数据库操作还可以很方便的与 model/view 架构进行整合.通常来说,我们对数据库的操作更多地在于对数据库表的操作,而这正是 model/view 架构的长项. Qt 使用QSqlDatabase表示一个数据