让 MyBatis 更好⽤的那些⼯具----MyBatis Generator

一、认识 MyBatis Generator

1MyBatis 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 对象

 六、代码

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]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一点知趣

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

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

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

打赏作者

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

抵扣说明:

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

余额充值