1. 程式人生 > 實用技巧 >springboot2.3+mybatis-plus+mysql8.0

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 */;