Springboot integrates Mybatis to realize addition, deletion, modification and check

Ordinary is just two words: laziness and laziness;
success is just two words: hardship and diligence;
excellence is just two words: you and me.
Follow me to learn JAVA, spring family bucket and linux operation and maintenance knowledge from 0, and take you from an ignorant teenager to the peak of life, and marry Bai Fumei!
Follow the WeChat public account [ IT is very reliable ], and share technical experience every day~  

 

Springboot integrates Mybatis to realize addition, deletion, modification and check

 1 Introduction      

      There are many persistence layer frameworks. Common persistence layer framework implementations include spring-data-jpa, mybatis (mybatis-plus) and hibernate. This tutorial will take the mybatis persistence layer framework as an example to detail the process of springboot integrating the mybatis framework, and finally realize the data addition, deletion and modification (CRUD) operation through annotation and xml.

 

2 What is mybatis?

      Explanation in the official mybatis document: MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJOs (Plain Old Java Objects) as records in the database through simple XML or annotations.

      That is, mybatis has done a lot of encapsulation of database operations, so that developers can use it immediately and reduce development costs. At the same time, mybatis supports both annotation and xml mapping methods, and also provides support for native sql.

 

3 Create a springboot project

      The process of creating a springboot project is very simple and is omitted here. The following is the directory structure of the springboot project that has been built.

      Project name: mybatis-demo

 

4 Install mysql database

4.1 Install mysql database      

      slightly! Pay attention to WeChat public account: IT is very reliable , reply " I want mysql installation tutorial " to receive it for free~

 

4.2 Create table and initialize data

      The mysql database connection information is as follows:

url: jdbc:mysql://localhost:3306/test_mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: root
password: root

       Created database table: user_t ,  add a unique index to the database table user_t. The index field is: mobile, and the index name: udx_user_mobile. The sql script to create the table is as follows:

CREATE TABLE `user_t`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `mobile` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户手机号',
  `user_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  `age` tinyint(4) NULL DEFAULT NULL COMMENT '年龄',
  `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '最后更新时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `udx_user_mobile`(`mobile`) USING BTREE COMMENT '用户手机号唯一索引'
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

 

     

      Let us first insert the following 4 pieces of data into the user_t database table for query testing!

INSERT INTO `user_t` VALUES (1, '13111111111', '张三', 10, '2020-10-22 15:58:51', '2020-10-22 18:26:31');
INSERT INTO `user_t` VALUES (2, '13555555555', '李四', 20, '2020-10-22 15:58:59', '2020-10-22 18:26:33');
INSERT INTO `user_t` VALUES (3, '13666666666', '王五', 20, '2020-10-22 15:59:15', '2020-10-22 18:26:35');
INSERT INTO `user_t` VALUES (4, '15222222222', '小六', 40, '2020-10-22 17:30:21', '2020-10-22 18:26:39');

 

 

5 springboot integration mybatis

5.1 Introducing the jar package

      Add mysql database driver, database connection pool and mybatis related dependency packages to the project pom.xml file.

    <!--持久化api依赖包:与数据库交互,比如Java bean和数据库表的对应关系-->
    <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
    </dependency>

    <!--mybatis依赖包-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.1</version>
    </dependency>

    <!-- mybatis通用Mapper依赖包:提供了基本的增删改查Mapper -->
    <dependency>
      <groupId>tk.mybatis</groupId>
      <artifactId>mapper-spring-boot-starter</artifactId>
      <version>1.2.4</version>
    </dependency>

    <!--mysql数据库驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>

    <!--Druid数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.10</version>
    </dependency>

 

5.2 Configure data source

      Add the following configuration in the application.properties or application.yml configuration file.

      1) Configure the data source

      2) Specify the path of the Mapper.xml resource file

      3) Open sql log

#mysql配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test_mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    username: root
    password: root

#指定Mapper.xml所在路径
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.hc.mybatisdemo.entity

#打印sql日志
logging:
  level:
    com:
      hc:
        mybatisdemo:
          mapper: debug

 

5.3 Scan Mapper interface

//注意这里需要引入tk.mybatis这个依赖
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.hc.mybatisdemo.mapper") //扫描的mapper包路径
public class MybatisDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(MybatisDemoApplication.class, args);
  }
}

 

6 Write code to add and delete CRUD

6.1 Create entity class

       Entity class:  User.java

import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * 用户实体类
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user_t")
public class User {

  /**
   * 主键id
   */
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  /**
   * 用户手机号
   */
  @Column(name = "mobile")
  private String mobile;

  /**
   * 用户名
   */
  @Column(name = "user_name")
  private String userName;

  /**
   * 年龄
   */
  @Column(name = "age")
  private Integer age;

  /**
   * 创建时间
   */
  @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") //写入数据库时格式化
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") //数据库查询后json格式化
  @Column(name = "create_time")
  private Date createTime;

  /**
   * 创建时间
   */
  @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
  @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
  @Column(name = "update_time")
  private Date updateTime;
}

 

6.2 Create Mapper Interface Class

      Mapper interface class: UserMapper.java

import com.hc.mybatisdemo.entity.User;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * UserMapper接口
 */
@Mapper
public interface UserMapper extends BaseMapper<User>, MySqlMapper<User> {

  /**
   * 根据id查询
   */
  User findById(Long id);

  /**
   * 根据用户名获取用户信息 注意:like模糊查询的占位符用${},不能用#{}
   */
  @Select(value = "select id, mobile, user_name as userName, age, create_time as createTime, update_time as updateTime from user_t where user_name like '%${userName}'")
  List<User> findByUserName(@Param("userName") String userName);

  /**
   * 更新id数据的用户名和年龄信息方式1
   */
  @Update(value = "update user_t set user_name = #{userName}, age = #{age} where id = #{id}")
  Integer updateById1(@Param("userName") String userName, @Param("age") Integer age, @Param("id") Long id);

  /**
   * 删除id数据方式1
   */
  @Delete(value = "delete from user_t where id = #{id}")
  Integer deleteById1(@Param("id") Long id);

  /**
   * 更新数据方式2
   */
  Integer updateById2(User user);

  /**
   * 删除id数据方式2
   *
   * @param id 被删除的数据id
   */
  Integer deleteById2(Long id);
}

 

6.3 Create UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hc.mybatisdemo.mapper.UserMapper">

  <resultMap id="BaseResultMap" type="com.hc.mybatisdemo.entity.User">
    <result column="id" jdbcType="VARCHAR" property="id"/>
    <result column="mobile" jdbcType="VARCHAR" property="mobile"/>
    <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    <result column="age" jdbcType="INTEGER" property="age"/>
    <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
    <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
  </resultMap>

  <select id="findById" resultMap="BaseResultMap">
    select * from user_t where id = #{id}
  </select>

  <!--<select id="findById" resultType="com.hc.mybatisdemo.entity.User">-->
  <!--select * from user_t where id = #{id}-->
  <!--</select>-->

  <update id="updateById" parameterType="com.hc.mybatisdemo.entity.User">
    update user_t set user_name = #{userName}, age = #{age} where id = #{id};
  </update>

  <delete id="deleteById" parameterType="String">
    delete from user_t where id = #{id};
  </delete>
</mapper>

 

6.4 Create Business Layer Interface Class

      Create a business layer interface class: IUserService.java

import com.hc.mybatisdemo.entity.User;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * 用户service接口
 */
@Service
public interface IUserService {

  /**
   * 查询一个
   */
  User findOne(Long id);

  /**
   * 根据用户名获取用户列表
   */
  List<User> findByUserName(String userName);

  /**
   * 插入一条数据
   */
  Integer insert(User user);

  /**
   * 更新一条数据
   */
  Integer updateById(User user);

  /**
   * 删除一条数据
   */
  Integer deleteById(Long id);

  /**
   * 事务控制测试--删除id1和id2两条数据
   */
  Integer transactionTest(Long id1, Long id2);
}

 

6.5 Create a business layer interface implementation class

      Create a business layer interface implementation class: UserServiceImpl.java

import com.hc.mybatisdemo.entity.User;
import com.hc.mybatisdemo.mapper.UserMapper;
import com.hc.mybatisdemo.service.IUserService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 用户service实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

  @Autowired
  private UserMapper userMapper;

  /**
   * 查询一个
   */
  @Override
  public User findOne(Long id) {
    return userMapper.findById(id);
  }

  /**
   * 根据用户名获取用户列表
   */
  @Override
  public List<User> findByUserName(String userName) {
    return userMapper.findByUserName(userName);
  }

  /**
   * 新增一条数据
   */
  @Override
  public Integer insert(User user) {
    return userMapper.insertSelective(user);
  }

  /**
   * 更新一条数据
   */
  @Override
  public Integer updateById(User user) {
//        return userDao.updateById1(user.getUserName(), user.getAge(), user.getId());
    return userMapper.updateById2(user);
  }

  /**
   * 删除一条数据
   */
  @Override
  public Integer deleteById(Long id) {
//        return userDao.deleteById1(id);
    return userMapper.deleteById2(id);
  }

  /**
   * 事务控制测试--删除id1和id2两条数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Integer transactionTest(Long id1, Long id2) {
    try {
      userMapper.deleteById1(id1);
      userMapper.deleteById1(id2);
      int a = 0;
      int b = 10 / a;//模拟抛出异常
    } catch (Exception e) {
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return 0;
    }
    return 1;
  }
}

 

6.6 Create control layer api class

      Create the control layer api class: UserController.java

import com.hc.mybatisdemo.entity.User;
import com.hc.mybatisdemo.service.IUserService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户控制器
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

  @Autowired
  private IUserService userService;

  /**
   * 根据id查询
   */
  @GetMapping(value = "findOne")
  public User findOne(Long id) {
    User user = userService.findOne(id);
    return user;
  }

  /**
   * 根据用户名获取用户列表
   */
  @GetMapping(value = "findByUserName")
  public List<User> findByUserName(String userName) {
    return userService.findByUserName(userName);
  }

  /**
   * 新增一条数据
   */
  @PostMapping(value = "insert")
  public Integer insert(@RequestBody User user) {
    return userService.insert(user);
  }

  /**
   * 更新一条数据
   */
  @PutMapping(value = "update")
  public Integer update(@RequestBody User user) {
    return userService.updateById(user);
  }

  /**
   * 根据用户名获取用户列表
   */
  @DeleteMapping(value = "delete")
  public Integer delete(Long id) {
    return userService.deleteById(id);
  }

  /**
   * 事务控制测试
   */
  @GetMapping(value = "transactionTest")
  public Integer transactionTest(Long id1, Long id2) {
    return userService.transactionTest(id1, id2);
  }
}

 

7 Test API

7.1 Query a piece of data based on id

      Query the data with id 2.

 

7.2 Fuzzy query

      Left fuzzy query. Query the user name data ending with "Five".

 

7.3 Save a piece of data

      Insert a record with the user name "Old Seven".

      Save the result:

 

7.4 Update a piece of data

      Update the user name of the data with id 5 to "Old Qiqi" and the age to 75.

      Results after update:

 

7.5 Delete a piece of data

      Delete the data with id 5.

      Results after deletion:

 

7.6 Transaction control (Transaction) test

      Call the transaction control test api interface (the business layer of the interface will delete the two data with id 1 and 2), but we artificially buried a code that throws an exception (int b = 10/a;). Ideal result: because the code throws an exception, then neither of the two pieces of data will be deleted, because the transaction is rolled back!

      Call the interface and delete the two data with id 1 and 2:

      The test results are as follows, it can be seen that the transaction is rolled back. Data with id 1 and 2 were not deleted successfully. Prove the atomicity and consistency of MySQL operations in the same transaction.

      Follow the WeChat public account and reply " I want mybatis integrated source code " to get the mybatis-demo source code of this tutorial for free~

Guess you like

Origin blog.csdn.net/IT_Most/article/details/109198677