MyBatis:Generator

MyBatis

Generator

介绍网址:Introduction to MyBatis Generator

Generator ,一个用于 MyBatis 的代码生成工具,可以根据数据库表结构自动生成对应的实体类、DAO 接口和 SQL 映射文件,提高开发效率和代码质量。同时,MyBatis Generator 还支持自定义生成规则,可以按照自己的需求进行配置。

简单示例:

首先,在 pom.xml 中添加依赖

xml 复制代码
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.4.0</version>
</dependency>

接着,在 resources 目录下创建一个 Generator 的配置文件 mybatis_generator.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!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="DB2Tables" targetRuntime="MyBatis3">

        <commentGenerator>
            <!-- 是否去除自动生成的注释 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- MySQL数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatisdemo?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC"
                        userId="root"
                        password="0123" />

        <!-- Java 类型解析器,一般默认为 false -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- Domain 生成器:生成实体类。属性 targetProject :生成 POJO 类的位置;其余默认 -->
        <javaModelGenerator targetPackage="cn.edu.MyBatisDemo.model" targetProject=".\src\main\java" />

        <!-- Mapping 生成器:生成映射文件。属性 targetProject :mapper 映射文件生成的位置;其余默认 -->
        <sqlMapGenerator targetPackage="cn.edu.MyBatisDemo.mapper" targetProject=".\src\main\java">
            <!-- enableSubPackages :是否让 schema 作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- Mapper 生成器:生成接口。targetProject 属性:mapper 接口生成的的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="cn.edu.MyBatisDemo.mapper" targetProject=".\src\main\java">
            <!-- enableSubPackages :是否让 schema 作为包的后缀 -->
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>

        <!-- 指定数据表。tableName 属性:指定数据库的表名;domainObjectName 属性:生成对应实体类的名字;...Example 属性:设置关闭即可 -->
        <table tableName="mybatis_generator"
               domainObjectName="MyBatisGenerator"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false" />
    </context>

</generatorConfiguration>

然后,只需在数据库中创建一个数据表 mybatis_generator 。表名称需要与 mybatis_generator.xml 的 table 标签中的 tableName 属性值对应

表结构信息如图:

最后,测试结果

java 复制代码
package cn.edu.MyBatisDemo.test;

import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MyBatisGeneratorTest {
    @Test
    public void mbgTest() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;

        // 只需修改 Generator 的配置文件名称即可
        String path = this.getClass().getClassLoader().getResource("mybatis_generator.xml").getPath();
        File configFile = new File(path);

        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

结果如图(实体类、接口与映射文件会自动生成在设定的目录下):

接口中声明一系列方法介绍如图:

附

在上面案例的基础下,简单实现批量操作与分页查询。

批量操作

首先,在实体类 MyBatisGenerator 中添加无参构造方法、有参构造方法与 toString() 方法

java 复制代码
public MyBatisGenerator() {
   super();
}

public MyBatisGenerator(Integer id, String name, Integer age, String hobby, String career) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.hobby = hobby;
    this.career = career;
}

@Override
public String toString() {
    return "MyBatisGenerator{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", age=" + age +
            ", hobby='" + hobby + '\'' +
            ", career='" + career + '\'' +
            '}';
}

然后,在测试类 MyBatisGenerator 中添加批量操作测试方法

java 复制代码
@Test
public void test() throws IOException {
    //1.根据配置文件创建数据库连接会话的工厂类
    InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
    //获取工厂类
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    //2.通过工厂类获取数据库连接的会话
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);

    //3.通过 sqlSession 操作数据库
    try {
        MyBatisGeneratorMapper myBatisGeneratorMapper = sqlSession.getMapper(MyBatisGeneratorMapper.class);
        for (int i = 0 ; i < 36 ; i++){
            //实体类的名字 MyBatisGenerator 与导入的 org.mybatis.generator.api.MyBatisGenerator 名字重复。故此写上 cn.edu.MyBatisDemo.model.
            myBatisGeneratorMapper.insert(new cn.edu.MyBatisDemo.model.MyBatisGenerator(20230901+i,"Q"+i,18,"看书","歌手"));
        }
        sqlSession.commit();
    } finally {
        sqlSession.close();
    }
}

注:在创建会话中传入参数 ExecutorType.BATCH(设定采用批量操作的方式执行 SQL 语句)

最后,测试结果

结果如图:

分页查询

MyBatis 分页插件 PageHelper 作者 --- isea533
Mybatis-PageHelper 网址

首先,在 pom.xml 中添加依赖

xml 复制代码
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.3.2</version>
</dependency>

接着,在全局配置文件 mybatis.xml 中配置插件

xml 复制代码
<!-- plugins 标签需要在 environments 标签前 -->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>

然后,在接口 MyBatisGeneratorMapper 中声明获取所有用户信息的方法。同时,在映射文件 MyBatisGeneratorMapper.xml 中实现方法

xml 复制代码
<select id="selectAll" resultType="myBatisGenerator" >
  select
    <include refid="Base_Column_List" />
  from mybatis_generator
</select>

最后,测试结果

存储过程

在 MySQL调优 文章中,了解过存储过程。接下来,简单介绍 MyBatis 如何调用存储过程。

首先,创建一个存储过程 mybatis_generator_storedProcedure

sql 复制代码
DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    PROCEDURE `mybatisdemo`.`mybatis_generator_storedProcedure`(IN start_id INT,IN end_id INT)
    BEGIN
		SELECT `id`,`name`,`age`,`hobby`,`career` FROM `mybatis_generator` WHERE `id` >= start_id AND `id` <= end_id;
    END$$

DELIMITER ;

然后,在接口 MyBatisGeneratorMapper 中声明通过调用存储过程获取指定用户信息的方法。同时,在映射文件 MyBatisGeneratorMapper.xml 中实现方法

java 复制代码
 public List<MyBatisGenerator> selectByStoredProcedure(@Param("start_id") int start_id,@Param("end_id") int end_id); //通过调用存储过程获取指定用户的信息
xml 复制代码
<!-- 指定 statementType 属性值为 CALLABLE -->
<select id="selectByStoredProcedure" resultType="myBatisGenerator" statementType="CALLABLE" >
  {call mybatis_generator_storedProcedure(
      #{start_id,mode=IN,jdbcType=INTEGER},
      #{end_id,mode=IN,jdbcType=INTEGER}
  )}
</select>

最后,测试结果

相关推荐
郭小李4 小时前
mybatis 动态 sql
java·sql·mybatis
知守观4 小时前
技术考古:iBATIS 2.3.4 时代的持久层,是如何用 Map 玩转 307 个存储过程的?
java·后端·mybatis
captain3765 小时前
MyBatis Plus(1)
java·服务器·mybatis
代码不停11 小时前
MyBatis进阶
spring boot·mybatis
captain37620 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
captain3761 天前
MyBatis(进阶1)
mybatis
郭小李1 天前
mybatis的 Mapper.xml语法
xml·java·mybatis
m0_639906941 天前
MyBatis 实现分页查询|逻辑分页、物理分页、PageHelper 原理
mybatis
captain3762 天前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
FungLeo2 天前
成为全栈·Go 后端篇·文章查询与展示投影:安全分页、排序和软删除
golang·go·gorm·分页查询·成为全栈·sql安全