• springboot2.3+mybatis-plus+mysql8.0


    系统环境:

    操作系统: win10

    jdk版本:

    openjdk version "12" 2019-03-19
    OpenJDK Runtime Environment (build 12+33)
    OpenJDK 64-Bit Server VM (build 12+33, mixed mode, sharing)

    idea版本:

    IntelliJ IDEA 2020.2.1 (Ultimate Edition)
    Build #IU-202.6948.69, built on August 25, 2020
    Licensed to hello
    Subscription is active until September 11, 2021
    For educational use only.
    Runtime version: 11.0.8+10-b944.31 amd64
    VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
    Windows 10 10.0
    GC: ParNew, ConcurrentMarkSweep
    Memory: 966M
    Cores: 8
    Non-Bundled Plugins: Lombook Plugin, com.intellij.kubernetes, training

    maven版本:3.6.3

    1. 项目结构如下:
    2. pom.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.3.3.RELEASE</version>
              <relativePath/> <!-- lookup parent from repository -->
          </parent>
          <groupId>com.example</groupId>
          <artifactId>mybatisdemo</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>mybatisdemo</name>
          <description>Demo project for Spring Boot</description>
      
          <properties>
              <java.version>14</java.version>
          </properties>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.mybatis.spring.boot</groupId>
                  <artifactId>mybatis-spring-boot-starter</artifactId>
                  <version>2.1.3</version>
              </dependency>
              <dependency>
                  <groupId>org.springframework.session</groupId>
                  <artifactId>spring-session-core</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-freemarker</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-devtools</artifactId>
                  <scope>runtime</scope>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
      <!--            <scope>runtime</scope>-->
                  <version>8.0.16</version>
              </dependency>
      <!--        mp-->
              <dependency>
                  <groupId>com.baomidou</groupId>
                  <artifactId>mybatis-plus-boot-starter</artifactId>
                  <version>3.4.0</version>
              </dependency>
              <dependency>
                  <groupId>com.baomidou</groupId>
                  <artifactId>mybatis-plus-generator</artifactId>
                  <version>3.4.0</version>
              </dependency>
              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
                  <exclusions>
                      <exclusion>
                          <groupId>org.junit.vintage</groupId>
                          <artifactId>junit-vintage-engine</artifactId>
                      </exclusion>
                  </exclusions>
              </dependency>
          </dependencies>
      
          <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                  </plugin>
              </plugins>
          </build>
      
      </project>
    3. application.yml

      spring:
      #  profiles:
      #    active: dev
        datasource:
          username: root
          password: capgemini@123
          url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
      server:
        port: 8080
      mybatis:
        mapper-locations: classpath:mapper/*.xml
        type-aliases-package: com.example.mybatisdemo.entity
        configuration:
          map-underscore-to-camel-case: true
      
      # Logger Config
      logging:
        level:
          com.baomidou.mybatisplus.samples: debug
          com.example.mybatisdemo: debug
    4. mapper.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.example.mybatisdemo.dao.UserMapper">
      
          <!-- 通用查询映射结果 -->
          <resultMap id="BaseResultMap" type="com.example.mybatisdemo.entity.User">
              <result column="id" property="id" />
              <result column="name" property="name" />
          </resultMap>
      
          <sql id="tName">
              user
          </sql>
      
          <!-- 通用查询结果列 -->
          <sql id="Base_Column_List">
              id,
              name
          </sql>
      
          <select id="getOne" resultMap="BaseResultMap">
              SELECT
                  <include refid="Base_Column_List"></include>
              FROM
                  user
              WHERE
                  id=#{id}
          </select>
      
          <select id="getFirst" resultMap="BaseResultMap">
              SELECT
              <include refid="Base_Column_List"></include>
              FROM
                  user
              <where>
                  <if test="name!=null">
                      ,`name`=#{name}
                  </if>
              </where>
              LIMIT 1
          </select>
      
          <insert id="saveNotExist" useGeneratedKeys="true" keyProperty="id">
              INSERT INTO
                user
                (`name`) VALUES (#{name})
          </insert>
          <update id="saveExist">
              UPDATE
              user
              <set>
                  <if test="name!=null">
                      ,name=#{name}
                  </if>
                  ,id=#{id}
              </set>
              WHERE
                  id=#{id}
          </update>
          <delete id="deleteOne" parameterType="long">
              DELETE FROM
                  user
                  WHERE id=#{id}
          </delete>
      </mapper>
    5. dao

      package com.example.mybatisdemo.dao;
      
      import com.example.mybatisdemo.entity.User;
      import com.baomidou.mybatisplus.core.mapper.BaseMapper;
      import org.apache.ibatis.annotations.Options;
      import org.springframework.stereotype.Repository;
      
      /**
       * <p>
       *  Mapper 接口
       * </p>*/
      @Repository
      public interface UserMapper extends BaseMapper<User> {
      
          @Override
          @Options(useGeneratedKeys = true, keyProperty = "id")
          int insert(User entity);
      
          User getOne(User entity);
      
          int saveNotExist(User entity);
      
          int saveExist(User entity);
      
          int deleteOne(Long id);
      
          User getFirst(User entity);
      }
    6. 单元测试 (注意:如果想让单元测试自动回滚,请在方法上添加注解   @Transactional(rollbackFor = {Exception.class}) 

      package com.example.mybatisdemo;
      
      import com.example.mybatisdemo.dao.UserMapper;
      import com.example.mybatisdemo.entity.User;
      import lombok.extern.slf4j.Slf4j;
      import org.junit.jupiter.api.Test;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.test.context.SpringBootTest;
      import org.springframework.util.Assert;
      
      @SpringBootTest
      @Slf4j
      class MybatisdemoApplicationTests {
      
          @Test
          void contextLoads() {
          }
      
          @Autowired
          private UserMapper userMapper;
      
          @Test
          void queryOneTest(){
             User u = userMapper.selectById(2L);
              Assert.notNull(u,"cannot find row!");
              log.info(u.getName());
          }
      
          @Test
          void insertOneTest(){
              User u = new User();
              u.setName("王一");
      
              userMapper.insert(u);
              Assert.notNull(u.getId(),"id已回写");
              log.info(u.getId().toString());
      
          }
      
          @Test
          void TestGetOne(){
              User user = new User();
              user.setId(2L);
              Assert.isTrue(userMapper.getOne(user).getName().equals("王一"),"getUser:id=2L,name=王一");
          }
      
          @Test
          void TestSaveNotExist(){
              User user = new User();
              user.setName("自定义添加");
              userMapper.saveNotExist(user);
              Assert.notNull(user.getId(),"id回写"+user.getId());
          }
      
          @Test
          void TestSaveExist(){
              User user = new User();
              user.setId(1L);
              user.setName("第一条数据,已更新2");
      
              userMapper.saveExist(user);
              User u = userMapper.getOne(user);
              Assert.isTrue(u.getName().equals("第一条数据,已更新2"),"是第一条没错了");
          }
      
          @Test
          void TestSaveExistEmpty(){
              User user = new User();
              user.setId(1L);
              userMapper.saveExist(user);
              User u = userMapper.getOne(user);
              log.info(u.toString());
          }
      
          @Test
          void TestDeleteOne(){
              User u = userMapper.getFirst(new User());
              Assert.notNull(u.getId(),"非空");
      
              Assert.isTrue(userMapper.deleteOne(u.getId())>0,"删除失败");
          }
      
      }

      7. 建表语句

      -- --------------------------------------------------------
      -- 主机:                           127.0.0.1
      -- 服务器版本:                        8.0.21 - MySQL Community Server - GPL
      -- 服务器操作系统:                      Win64
      -- HeidiSQL 版本:                  11.0.0.5919
      -- --------------------------------------------------------
      
      /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
      /*!40101 SET NAMES utf8 */;
      /*!50503 SET NAMES utf8mb4 */;
      /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
      /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
      
      -- 导出  表 test.role 结构
      DROP TABLE IF EXISTS `role`;
      CREATE TABLE IF NOT EXISTS `role` (
        `id` bigint NOT NULL AUTO_INCREMENT,
        `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
      
      -- 数据导出被取消选择。
      
      -- 导出  表 test.user 结构
      DROP TABLE IF EXISTS `user`;
      CREATE TABLE IF NOT EXISTS `user` (
        `id` bigint NOT NULL AUTO_INCREMENT,
        `name` varchar(50) NOT NULL DEFAULT '',
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
      
      -- 数据导出被取消选择。
      
      -- 导出  表 test.user_role 结构
      DROP TABLE IF EXISTS `user_role`;
      CREATE TABLE IF NOT EXISTS `user_role` (
        `rid` bigint NOT NULL,
        `uid` bigint NOT NULL,
        KEY `FK_user_role_role` (`rid`),
        KEY `FK_user_role_user` (`uid`),
        CONSTRAINT `FK_user_role_role` FOREIGN KEY (`rid`) REFERENCES `role` (`id`) ON DELETE CASCADE,
        CONSTRAINT `FK_user_role_user` FOREIGN KEY (`uid`) REFERENCES `user` (`id`) ON DELETE CASCADE
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
      
      -- 数据导出被取消选择。
      
      /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
      /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
      /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
  • 相关阅读:
    jQuery
    MySQL的引入,绿色包下载和应用
    jsp引用JSTL核心标签库
    Servlet的引入
    Servlet访问Javabean并传结果给jsp
    Spring MVC 中获取session的几种方法
    面试必问系列——hashmap的默认扩容阈值是大于12还是大于等于12
    面试必问系列——重写equals为什么一定要重写hashcode
    分析spring4和spring5日志中的不同
    mysql 查询参数尾部有空格时被忽略
  • 原文地址:https://www.cnblogs.com/tu13/p/springboot_mybatis_mysql8.html
Copyright © 2020-2023  润新知