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种配置的方式
第一种,这个是全局的,针对所有表
第二种,这个只针对表中某一列