微信搜索【程序员囧辉】,关注这个坚持分享技术干货的程序员。
前言
当我们新建一个表时,在项目中至少要新建3个文件:实体类*PO.java、接口类*POMapper.java、存放SQL的接口实现类*POMapper.xml。对于字段少的表来说,可能你不会在意,但是如果是一个字段超过几十个的表,那你可能要写的头昏眼花了。并且,当字段多了,手写错误的几率特别大。这个时候,我们就需要MyBatis来自动生成。
基本使用
1.新建配置文件
在src/main/resource/config/mybatis目录下新建配置文件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>
<context id="MysqlTables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- jdbc链接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/joonwhee?
autoReconnect=true&autoReconnectForPools=true&
useUnicode=true&characterEncoding=utf-8"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成PO类的位置 -->
<javaModelGenerator targetPackage="com.dianping.open.joonwhee.po"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="config.mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.dianping.open.joonwhee.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 指定要生成的表 -->
<table tableName="User" domainObjectName="UserPO">
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
2.pom文件中引入plugin
引入mybatis自动生成的插件,放在build->plugin标签下,如下:
3.双击使用插件
在Maven Projects页面找到项目的mybatis-generator插件,双击&