1. 程式人生 > 其它 >SpringBoot整合MyBatis 使用Generatot外掛

SpringBoot整合MyBatis 使用Generatot外掛

SpringBoot整合MyBatis

使用MyBatis Generatot外掛

系統要求

Java 8+

springBoot2.5 +

建立springBoot專案工程

匯入依賴
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <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.2.0</version>
    </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>
        <version>8.0.25</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>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.0</version>
            <dependencies>
                <dependency>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                    <version>3.5.7</version>
                </dependency>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.25</version>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <id>Generate MyBatis Artifacts</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <overwrite>true</overwrite>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
檢視是否有MyBatis Generator外掛
配置application.yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3307/webapp1
#    ?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: webapp1
    password: webapp1

    #Spring Boot 預設是不注入這些屬性值的,需要自己繫結
    #druid 資料來源專有配置
    # 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 200
    # 配置獲取連線等待超時的時間
    maxWait: 60000
    # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一個連線在池中最小生存的時間,單位是毫秒
    minEvictableIdleTimeMillis: 300000
    # 用來檢測連線是否有效的sql,要求是一個查詢語句
    validationQuery: SELECT 1 FROM DUAL
    # 建議配置為true,不影響效能,並且保證安全性。申請連線的時候檢測,如果空閒時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連線是否有效。
    testWhileIdle: true
    # 申請連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能
    testOnBorrow: false
    # 歸還連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能。
    testOnReturn: false
    # 是否快取preparedStatement,也就是PSCache。PSCache對支援遊標的資料庫效能提升巨大,比如說oracle。在mysql下建議關閉。
    poolPreparedStatements: true
    # 要啟用PSCache,必須配置大於0,當大於0時,poolPreparedStatements自動觸發修改為true。
    max-pool-prepared-statement-per-connection-size: 50

    #配置監控統計攔截的filters,stat:監控統計、log4j:日誌記錄、wall:防禦sql注入
    #如果允許時報錯  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #則匯入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    # 合併多個DruidDataSource的監控資料
    useGlobalDataSourceStat: true
    # 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

mybatis:
  #sql對映檔案的位置
  #  mapper-locations: classpath:com/xiang/mapper/*.xml
  mapper-locations: classpath:mapper/*.xml
  #開啟駝峰命名轉化
  configuration:
    map-underscore-to-camel-case: true
  #開啟別名
#  type-aliases-package: com.xiang

配置generatorConfig.xml
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="simple" targetRuntime="MyBatis3Simple">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3307/webapp1"
                        userId="webapp1" password="webapp1"/>
        <!-- useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"-->

<!--        <commentGenerator>-->
<!--            &lt;!&ndash; 是否去除自動生成的註釋 true:是 : false:否 &ndash;&gt;-->
<!--            <property name="suppressAllComments" value="false" />-->
<!--        </commentGenerator>-->

        <javaModelGenerator targetPackage="com.xiang.model" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="com.xiang.mapper" targetProject="src/main/resources"/>

        <javaClientGenerator targetPackage="com.xiang.mapper" targetProject="src/main/java" type="XMLMAPPER"/>

        <table tableName="user"/>
    </context>
</generatorConfiguration>

編寫mapper、model 這兩個包。

(只寫包名就好)包下邊的實體類、與介面、xml檔案使用外掛生成

如圖所示:

現在點選外掛

生成實體類、與介面、xml檔案

生成的檔案如圖所示
接下來建立service、controller層
編寫UserService
package com.xiang.service;

import com.xiang.model.User;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/19 11:24
 */
public interface UserService {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    User selectByPrimaryKey(Integer id);

    List<User> selectAll();

    int updateByPrimaryKey(User record);
}

編寫UserServiceImpl
package com.xiang.service.impl;

import com.xiang.mapper.UserMapper;
import com.xiang.model.User;
import com.xiang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/19 11:27
 */
@Repository
public class UserServiceImpl implements UserService{
    @Autowired
    UserMapper userMapper;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }
}

執行測試UserServiceImpl
package com.xiang.service;

import com.xiang.mapper.UserMapper;
import com.xiang.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/10/19 11:30
 */

/**
 * int deleteByPrimaryKey(Integer id);
 * int insert(User record);
 * User selectByPrimaryKey(Integer id);
 * List<User> selectAll();
 * int updateByPrimaryKey(User record);
 */
@SpringBootTest
public class UserServiceImpl {
    @Autowired
    UserService userService;

    /**
     * 查所有
     */
    @Test
    public void selectAll() {
        List<User> list = userService.selectAll();
        for (User user : list) {
            System.out.println(user);
        }
    }
}

執行結果