前言
mybatis_Generator插件的使用可以帮助我们自动生成po层和dao层的代码,大大节省了程序员的精力。
环境
idea 2018.2 java1.8
Mybatis_Generator插件的使用
新建webapp项目,在main目录下,建立java目录和resources目录
在resources目录下,添加mybatis-generator-config.xml配置文件
可以看出图中约束报错了,解决方法有两种,光标移到代码上出现红色小灯泡,点击Fetch external resources,如果不报错了,则跳过下面的内容,否则将约束文件下到本地,然后找到文件,应用即可(可能需要重启一下,视情况而定)
按照注释,修改为自己要生成的数据库表的po和dao层代码
<?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>
<!--1mysql 连接数据库jar 这里选择自己本地位置-->
<classPathEntry location="E:/idea/.m2/repository/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar" />
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 2是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--3数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 4targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.sdut.mybatis.po"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 5targetProject:mapper映射文件生成的位置
如果maven工程只是单独的一个工程,targetProject="src/main/java"
若果maven工程是分模块的工程,targetProject="所属模块的名称",例如:
targetProject="ecps-manager-mapper",下同-->
<sqlMapGenerator targetPackage="cn.sdut.mybatis.dao"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 6targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.sdut.mybatis.dao"
targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 7指定数据库表 -->
<table tableName="dept"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="true"
enableUpdateByExample="false"
>
<property name="modelOnly" value="false" />
</table>
<table
tableName="emp"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="true"
enableUpdateByExample="false"
>
<property name="modelOnly" value="false" />
</table>
</context>
</generatorConfiguration>
在pom.xml文件里面配置插件
<!--mybatis自动生成器的 插件开始-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>