MyBatis Generator,帮你少写50%代码的自动化工具,2021年Java网络编程总结篇

org.mybatis.generator

mybatis-generator-maven-plugin

1.3.7

true

true

在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,这里省略了一部分配置

这样生成的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被映射为Lo

【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

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

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

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值