其他分享
首页 > 其他分享> > 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);
        }
    }
}

运行结果

标签:Generatot,插件,SpringBoot,boot,User,import,org,xiang,com
来源: https://www.cnblogs.com/d534/p/15426497.html