如何优雅的使用MyBatis Generator

在这里插入图片描述

介绍

MyBatis Generator的作用就是根据数据库中的表结构,帮我们自动生成和表结构相同的实体类,mapper接口,包含基本增删改查语句的XML文件,我以一个例子演示如何优雅的使用MyBatis Generator,我会把例子放在GitHub上,所以不用担心配置看不全的问题。

造数据,新建一个Spring Boot项目

建一个学生表,插入四条数据

CREATE TABLE `student` (
  `id` int(11) NOT NULL COMMENT '学生id',
  `name` varchar(255) NOT NULL COMMENT '学生姓名',
  `gender` tinyint(2) DEFAULT NULL COMMENT '学生性别,1男生,0女生',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
insert into student (id, name, gender) values (1, '张三', 1);
insert into student (id, name, gender) values (2, '李四', 1);
insert into student (id, name, gender) values (3, '王五', 1);
insert into student (id, name, gender) values (4, '赵六', 1);

建一个Spring Boot项目
在这里插入图片描述

配置maven插件,增加配置文件,运行插件

配置maven插件

<build>
	<plugins>
		<plugin>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-maven-plugin</artifactId>
			<version>1.3.7</version>
			<configuration>
				<verbose>true</verbose>
				<overwrite>true</overwrite>
			</configuration>
		</plugin>
	</plugins>
</build>

在resources目录下放配置文件,我这里放了2个文件,datasource.properties和generatorConfig.xml,其中datasource.properties中放了一个数据库的配置,如用户名和密码之类的,generatorConfig.xml引用datasource.properties其中的配置,剩下的文件夹和类都是配置好后,运行插件自动生成的
在这里插入图片描述
运行插件的方法如下,点击红框部分即可
MyBatis Generator的运行方法有很多种,maven插件的方法最方便,因此不再介绍其他方法
在这里插入图片描述
生成的Student类和数据库中的字段一样,而StudentExample类是为了方便增删改查而生成的,我演示一下用法,其实很鸡肋,一般不用这个

@Repository
public interface StudentMapper {

	// 生成的一部分,没有全部列出来
    long countByExample(StudentExample example);

    int deleteByExample(StudentExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);
}

演示

我建一个测试类,来演示用法,IDEA中按住Ctrl+Shift后再按T键,自动生成一个测试类
,选中要测试的方法即可自动生成测试类,我就演示一下countByExample这个方法吧
在这里插入图片描述
在这里插入图片描述
查询id>=1并且id<4的学生的数量,测试通过

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentMapperTest {

    @Autowired
    StudentMapper studentMapper;

    @Test
    public void countByExample() throws Exception {

        StudentExample example = new StudentExample();
        StudentExample.Criteria criteria = example.createCriteria();
        // id >= 1
        criteria.andIdGreaterThanOrEqualTo(1);
        // id < 4
        criteria.andIdLessThan(4);
        assertEquals(3, studentMapper.countByExample(example));
    }

}

可以看到SQL的逻辑用Java代码表示了,不容易维护。所以一般是配置不生成Example类

在generatorConfig.xml配置文件中配置项设为false即可,完整版看GitHub,这里省略了一部分配置

<table tableName="student" enableCountByExample="false" enableUpdateByExample="false">
</table>

这样生成的Mapper文件中就只包含最基础的增删改查,没有这些乱七八糟的Example了
下面就是修改后生成的全部内容,是不是看着清爽多了

public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

如何定义Java类型和数据库类型的映射关系

还是上面的例子,我生成的Student对象如下

public class Student {
    private Integer id;

    private String name;

    private Byte gender;

    private LocalDateTime createTime;
}

数据库中的datetime被映射为LocalDateTime 类型(用起来比较方便),这是我配置的原因。默认的是、datetime被映射为Date类型

在generatorConfig.xml有2种配置的方式

第一种,这个是全局的,针对所有表

<javaTypeResolver>
    <property name="useJSR310Types" value="true"/>
</javaTypeResolver>

第二种,这个只针对表中某一列

<table tableName="student" domainObjectName="Student">
	<columnOverride column="create_time" javaType="java.time.LocalDateTime"/>
</table>

这两种方式还可以定义其他类型的映射方式,我就不再介绍了。知道方法查询具体配置就行

后记

话说刚开始用MyBatis Generator的坑还是挺多的,要不就是在低版本的插件中,这个配置不起作用

<javaTypeResolver>
    <property name="useJSR310Types" value="true"/>
</javaTypeResolver>

要不就是在最新的插件中,重新生成时,虽然配置了每次覆盖XML文件,但是不会起作用(这个一般都会配置,假如是追加的方式,会造成运行2次插件,一个接口在XML中对应2个语句,导致启动错误),还得配置作者为解决这个问题专门写的插件,为了大家少走弯路,我写了一个demo,各种配置写的很详细。基本上改改配置就能用,坑我都替大家填了。

github地址:
https://github.com/erlieStar/mybatis-generator-demo

参考博客

覆盖XML插件
[1]https://segmentfault.com/a/1190000013038272

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java识堂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值