GitHub项目地址
Gitee项目地址
使用 mybatis generator 自动生成代码,实现数据库的增删改查。
1 配置 Mybatis 插件
在 pom 文件添加依赖:
<plugins><plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.4</version> <configuration> <configurationFile>${basedir}/src/main/resources/mybatis-generator.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> </dependencies></plugin></plugins>
复制代码
更新依赖成功后,可以在 maven 中看到已经有了 mybatis 插件
img src="../0img/mybatis1.png" width="300px" />
2 创建库表
在数据库创建表格,具体方式见:https://mp.weixin.qq.com/s/ISCjsIpmccVnuvXPkiFLMw
3 配置参数
src/main/resources/mybatis-generator.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> <context id="context" targetRuntime="MyBatis3">
<!-- 去除自动生成注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> </commentGenerator>
<!-- 数据库的相关配置 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/sys" userId="root" password="root"/>
<javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver>
<!-- 实体类生成的位置 --> <javaModelGenerator targetPackage="com.spring.boot.dao.model" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> <property name="trimStrings" value="true"/> </javaModelGenerator>
<!-- *Mapper.xml 文件的位置 --> <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator>
<!-- Mapper 接口文件的位置 --> <javaClientGenerator targetPackage="com.spring.boot.dao" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false"/> </javaClientGenerator>
<!-- 相关表的配置 --> <table tableName="user_data" domainObjectName="UserDataPo" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"/>
</context></generatorConfiguration>
复制代码
4 运行插件
双击 mybatis-generator:generate,运行插件。
img src="../0img/mybatis2.png" width="300px" />
可以看到已经生成了三个文件:
img src="../0img/mybatis3.png" width="300px" />
在 UserDataPoMapper.java 中,添加 @Mapper ,否则会出现报错。
5 编写其他代码
mybatis 自动生成了数据类、接口文件和 xml 文件,我们只需编写 controller 和 servic 层即可。
学习更多编程知识,请关注我的公众号:
代码的路
评论