一、认识 MyBatis Generator
1、MyBatis Generator(http://www.mybatis.org/generator/)
2、MyBatis
代码⽣成器
3、根据数据库表⽣成相关代码
A、
POJO
B、
Mapper
接⼝
C、
SQL Map XML
二、运⾏ MyBatis Generator的几种方式
1、命令⾏
•
java -jar mybatis-generator-core-x.x.x.jar -confifigfifile generatorConfifig.xml
2、Maven Plugin
(
mybatis-generator-maven-plugin
)
•
mvn mybatis-generator:generate
•
${basedir}/src/main/resources/generatorConfifig.xml
3、Eclipse Plugin
4、
Java程序
三、配置 MyBatis Generator
1、generatorConfiguration
A、context
•
jdbcConnection
•
javaModelGenerator
•
sqlMapGenerator
•
javaClientGenerator
(
ANNOTATEDMAPPER / XMLMAPPER / MIXEDMAPPER
)
•
table
四、⽣成时可以使⽤的插件(类似jPA的Lombok)
1、内置插件都在
org.mybatis.generator.plugins
包中
•
FluentBuilderMethodsPlugin
•
ToStringPlugin
•
SerializablePlugin
•
RowBoundsPlugin(分页)
五、使⽤⽣成的对象
•
简单操作,直接使⽤
⽣成的 xxxMapper
的⽅法
•
复杂查询,使⽤
⽣成的 xxxExample
对象
![](https://img-blog.csdnimg.cn/0fbffff333f9480bb902b0cd2b675b72.png)
六、代码
1、pom.xml
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
2、resource·下的generatorConfig.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><!--generatorConfiguration-->
<context id="H2Tables" targetRuntime="MyBatis3"><!--context-->
<!--配置顺序 plugin>jdbcConnection>javaModelGenerator>sqlMapGenerator>javaClientGenerator>table-->
<!--四个插件-->
<plugin type="org.mybatis.generator.plugins.FluentBuilderMethodsPlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin" />
<jdbcConnection driverClass="org.h2.Driver"
connectionURL="jdbc:h2:mem:testdb"
userId="sa"
password="">
</jdbcConnection>
<javaModelGenerator targetPackage="geektime.spring.data.mybatis.model"
targetProject="./src/main/java"><!--model层-->
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="geektime.spring.data.mybatis.mapper"
targetProject="./src/main/resources/mapper"><!--mapper层Java代码-->
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="MIXEDMAPPER"
targetPackage="geektime.spring.data.mybatis.mapper"
targetProject="./src/main/java"><!--由于MIXED混和,mapper层xml代码-->
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="t_coffee" domainObjectName="Coffee" ><!--表-->
<generatedKey column="id" sqlStatement="CALL IDENTITY()" identity="true" />
<columnOverride column="price" javaType="org.joda.money.Money" jdbcType="BIGINT"
typeHandler="geektime.spring.data.mybatis.handler.MoneyTypeHandler"/>
</table>
</context>
</generatorConfiguration>
以下是主类
package geektime.spring.data.mybatis;
@SpringBootApplication
@Slf4j
@MapperScan("geektime.spring.data.mybatis.mapper")
public class MybatisGeneratorDemoApplication implements ApplicationRunner {
@Autowired
private CoffeeMapper coffeeMapper;
public static void main(String[] args) {
SpringApplication.run(MybatisGeneratorDemoApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
generateArtifacts();//生成
// playWithArtifacts();
}
private void generateArtifacts() throws Exception {
List<String> warnings = new ArrayList<>();
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(
this.getClass().getResourceAsStream("/generatorConfig.xml"));
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
private void playWithArtifacts() {
Coffee espresso = new Coffee()
.withName("espresso")
.withPrice(Money.of(CurrencyUnit.of("CNY"), 20.0))
.withCreateTime(new Date())
.withUpdateTime(new Date());
coffeeMapper.insert(espresso);
Coffee latte = new Coffee()
.withName("latte")
.withPrice(Money.of(CurrencyUnit.of("CNY"), 30.0))
.withCreateTime(new Date())
.withUpdateTime(new Date());
coffeeMapper.insert(latte);
Coffee s = coffeeMapper.selectByPrimaryKey(1L);
log.info("Coffee {}", s);
CoffeeExample example = new CoffeeExample();//example
example.createCriteria().andNameEqualTo("latte");
List<Coffee> list = coffeeMapper.selectByExample(example);
list.forEach(e -> log.info("selectByExample: {}", e));
}
}
自动生成了model和mapper
结果
Coffee Coffee [Hash = 1183701566, id=1, name=espresso, price=CNY 20.00, createTime=Sun Apr 23 19:52:56 CST 2023, updateTime=Sun Apr 23 19:52:56 CST 2023]
selectByExample: Coffee [Hash = 832828638, id=2, name=latte, price=CNY 30.00, createTime=Sun Apr 23 19:52:56 CST 2023, updateTime=Sun Apr 23 19:52:56 CST 2023]