0x0 前言
MyBatis Generator可以帮助我们根据数据库表生成相应的实体类和Mapper,这大大减少了我们的代码量,提升了开发效率。
在Eclipse下安装一个MyBatis generator插件就就可以完美生成pojo和mapper;在idea下虽然也有相应的插件工具(功能也比较强大),但是如果我们想用原生的mybatis generator生成怎么做呢?官方的MyBatis Generator使用教程提供了多种方法,其中一种就是Maven插件。
0x1 使用教程
一、首先,要在pom文件中配置一个maven mybatis generator插件:
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>这里放你的generator配置文件路径</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
要注意的是,插件里要依赖你的jdbc驱动jar包。
二、 使用插件:
三、关于mybatis-generator配置文件
给个模板
<?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="context1">
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<commentGenerator>
<!-- 这个元素用来去除指定生成的注释中是否包含生成的日期 false:表示保护 -->
<!-- 如果生成日期,会造成即使修改一个字段,整个实体类所有属性都会发生变化,不利于版本控制,所以设置为true -->
<property name="suppressDate" value="true" />
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- jdbc四大件 -->
<jdbcConnection connectionURL="jdbc:mysql://localhost:3306/mall?useSSL=false"
driverClass="com.mysql.jdbc.Driver"
password="root"
userId="root" />
<javaTypeResolver>
<!-- This property is used to specify whether MyBatis Generator should
force the use of java.math.BigDecimal for DECIMAL and NUMERIC fields, -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成的pojo包名和路径 -->
<javaModelGenerator targetPackage="com.fly.pojo"
targetProject="src\main\java" >
</javaModelGenerator>
<!-- 映射文件 -->
<sqlMapGenerator targetPackage="com.fly.dao"
targetProject="src\main\resources" />
<!-- dao -->
<javaClientGenerator targetPackage="com.fly.dao"
targetProject="src\main\java" type="XMLMAPPER" />
<!-- 哪些表 -->
<table schema="yycg" tableName="tb_user" domainObjectName="User" mapperName="UserDao"/>
<table schema="yycg" tableName="tb_content" domainObjectName="Content" mapperName="ContentDao"/>
<table schema="yycg" tableName="tb_content_category" domainObjectName="ContentCategory" mapperName="ContentCategoryDao"/>
<table schema="yycg" tableName="tb_item" domainObjectName="Item" mapperName="ItemDao"/>
<table schema="yycg" tableName="tb_item_cat" domainObjectName="ItemCat" mapperName="ItemCatDao"/>
</context>
</generatorConfiguration>