当前位置:网站首页>What saved me 60% of my coding time? Use MBG
What saved me 60% of my coding time? Use MBG
2022-04-22 13:31:00 【Wanmao Society】
MyBatis Generator brief introduction
Business requirements are constantly changing , The structure of the database table is constantly modified , It's our destiny that we can't escape . A good workman does his work well , You must sharpen your tools first , It's time to sacrifice :MyBatis Generator( abbreviation :MBG), It's one for all versions MyBatis Automatic code generator for . It can automatically produce the corresponding entity class for the project according to the database table 、Mapper、DAO, Including simple CRUD Database operation ( establish 、 Inquire about 、 to update 、 Delete ). Free our hands , There's no need to do repetitive mechanical work . Save a lot of time , Don't have to work overtime , You can go on a date with sister paper .( If you have to have a sister first )
Create a MySQL surface
To facilitate the demonstration, create a MySQL surface , The table structure is relatively simple , It's a user information table :
CREATE TABLE `user_info` (
`id` bigint() NOT NULL AUTO_INCREMENT,
`name` varchar() DEFAULT NULL,
`age` int() DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Create a SpringBoot project
To use the IntelliJ IDEA For example , Create a SpringBoot project . Click on File->New->Projects…, choice Spring Initializr, Here's the picture :
Click on Next, Input Group、Artifact Etc , Here's the picture :
Click on Next, choice Web, And check the Spring Web, Here's the picture :
Click on Next, Input Project name、Project location Etc , Here's the picture :
Last , Click on Finish, One SpringBoot The project is created .
introduce MBG Of Maven plug-in unit
stay pom.xml Of plugins Add the following to the node :
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</plugin>
To configure MBG Of Maven plug-in unit
stay resources Create a generatorConfig.xml file , It reads as follows :
<?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>
<properties resource="application.properties"></properties>
<!--defaultModelType Used to specify the style of the generated object ,flat Indicates that each table generates only one entity class , This entity class contains all the fields in the table .-->
<context id="MySQLTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="javaFileEncoding" value="UTF-8"/>
<!-- The generated entity class implements the serialization interface -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<commentGenerator>
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</commentGenerator>
<!-- Database connection information -->
<jdbcConnection driverClass="${spring.datasource.driverClassName}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
</jdbcConnection>
<!-- Configure the location of the generated entity class -->
<javaModelGenerator targetPackage="one.more.mybatisgenerator.model" targetProject="src/main/java">
<!-- Is the setting setter In the method , Yes String Type field call trim() Method -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- Configure the interface location -->
<!-- type Set to ANNOTATEDMAPPER, Annotation based Mapper, There will be no corresponding xml File generation -->
<javaClientGenerator targetPackage="one.more.mybatisgenerator.mapper" targetProject="src/main/java"
type="ANNOTATEDMAPPER">
</javaClientGenerator>
<!-- Configuration database table -->
<table tableName="user_info">
<!-- In the generated insert Add on element useGeneratedKeys=”true” and keyProperty attribute -->
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
The above is the configuration of the most basic introduction , In the actual development process is enough . If you have partners, you need more configuration functions , Official website (https://mybatis.org/generator/configreference/xmlconfig.html) see .
Automatic code generation
Here are the most exciting moments , One click automatic code generation . stay Maven Plug in toolbar , You can see mybatis-generator plug-in unit , Double click on generate Options can be , Here's the picture :
After building successfully , You can see the generated code , Here's the picture :
Verify automatically generated code
There is one more step before verification, don't miss it , Is to add... To the startup class MapperScan annotation , such as :
@SpringBootApplication
@MapperScan("one.more.mybatisgenerator.mapper")
public class MybatisGeneratorDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisGeneratorDemoApplication.class, args);
}
}
The new data
Randomly generate one UserInfo Example , Insert into database :
public UserInfo add() {
Random random = new Random(System.currentTimeMillis());
UserInfo userInfo = new UserInfo();
userInfo.setName("name" + random.nextInt());
userInfo.setAge(random.nextInt());
userInfo.setCreateTime(new Date());
int rows = userInfoMapper.insert(userInfo);
System.out.println("rows:" + rows);
return userInfo;
}
Query data
Query the database age Greater than a certain value user_info data :
public List<UserInfo> getGreaterThan(Integer age) {
UserInfoExample example = new UserInfoExample();
Criteria criteria = example.createCriteria();
criteria.andAgeGreaterThan(age);
return userInfoMapper.selectByExample(example);
}
Complete sample source code
Complete sample source code can go to https://github.com/heihaozi/mybatis-generator-demo download .
版权声明
本文为[Wanmao Society]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221324098686.html
边栏推荐
- RT thread configuration SPI flash (w25q256)
- 指定Swagger接口文档中参数序列化组件为Newtonsoft.Json
- Model based RL overview
- redis持久化
- Scratch编程入门
- 封装统一响应结果枚举类(工具模块)
- EnvironmentPostProcessor怎么做单元测试?阿里P7解答
- [dark horse morning post] it is known that it is listed in Hong Kong today; Xiaohongshu responded to layoffs of 20%; The glory of the king was accused of plagiarism; Liu Jianhong's live broadcasting r
- PM4PY - 分析建议怎样的BPMN可以转换成Process Tree
- About chartjs screen size adaptation
猜你喜欢

PM4PY - 分析建议怎样的BPMN可以转换成Process Tree

Pm4py - analyze what BPMN can be converted into process tree

Redis如何查看单个key所占用的内存大小

Redis persistence

no main manifest attribute / .jar中没有主清单属性

Cube MX configuration SPI flash (w25q256)

Rust implements Fibonacci number

redis持久化

RedisConfig配置类

Ora-1652 cannot extend temp tablespace
随机推荐
算法---反转链表(Kotlin)
Station B cuts to the live broadcast, sooner or later
Communication principle of SPI protocol
数字孪生:如何撑起一个万亿市场的产业变革?
PM4PY - BPMN support
浅学一下Shell脚本(5)--函数,随机数,正则表达式
Redisconfig configuration class
Harbor v2.5更新,都增加了哪些功能?
MapReduce case - reverse order of uplink traffic (descending order)
上市公司营业收入数据集(1990-2021第三季度)
“开源之夏”活动火热报名中,丰厚奖金等你来拿
【黑马早报】知乎今日在港上市;小红书回应裁员20%;王者荣耀被指控抄袭;刘畊宏直播收入10天涨10倍;“知网反垄断第一案”已立案...
说了栈和队列的区别以后,面试官当场就吐了,同学们千万要引以为戒。
Redis memory usage info memory command parameter parsing
最大匹配数,最小路径覆盖数,最大独立数,最小点覆盖数 定理总结
微信小程序添加数据到数据库
快速串讲校招高频面试题——排序算法和复杂度
国元期货开户是否可靠?资金安全吗?
MySQL 使用存储过程添加数据
linux下redis6.详细安装