date: 2023-04-19 10:33
基于mybatis完成持久层代码生成步骤,设定开发环境为:idea: springboot+mybatis+mysql
1.在springboot项目中导入mybatis依赖
1 2 3 4 5 6 7 8 9
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
|
2.在springboot的resources包下添加generator/generatorConfig.xml文件,文件内容如下所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <?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> <context id="Mysql" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="autoDelimitKeywords" value="true"/> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/>
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" /> <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator>
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/courseimooc?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8" userId="courseimooc" password="courseimooc"> </jdbcConnection>
<javaModelGenerator targetProject="src\main\java" targetPackage="com.example.demo.domain"/>
<sqlMapGenerator targetProject="src\main\resources" targetPackage="mapper"/>
<javaClientGenerator targetProject="src\main\java" targetPackage="com.example.demo.mapper" type="XMLMAPPER" />
<table tableName="user" domainObjectName="User"/> </context> </generatorConfiguration>
|
注意上面末尾需要的三个位置,在对应的位置上对应生成好包。例如src\main\java下的com.example.demo.domain,src\main\java下的com.example.demo.mapper,src\main\resources下的mapper。
3. 在idea中添加配置,如图所示,按步骤就行,不做赘述
4. 补充操作:注意需要在mysql中提前创建好表用于生成
本文实例用户表,
1 2 3 4 5 6
| CREATE TABLE `user` ( `id` int NOT NULL, `name` varchar(255) NOT NULL, `phone` varchar(255) NOT NULL, PRIMARY KEY (`id`) );
|
5 springboot的application.yml中配置连接mysql
1 2 3 4 5
| spring.datasource.url=jdbc:mysql://localhost:3306/databaseName?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8 spring.datasource.username=userName spring.datasource.password=userPassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis.mapper-locations=classpath:/mapper/*.xml
|
最后运行配置好的mybatis-generator即可
生成器将自动完成依据mysql和domian中的user结构和目录信息,生成对应表的domain/UserExample.java、mapper/UserMapper.java、mapper/userMapper.xml。
总结
以上步骤主要基于mybatis和maven完成单表持久层代码的生成,后续利用thymleaf搭配controller、service及前端的代码生成器,可以一键完成前后端单表代码生成。