项目中用的mybatis,依据数据库表手工写java实体类、mapper接口及mapper xml文件,是一件很郁闷的乏味的事情,而且容易出错,下面记录了一下本人用工具类自动生成这些文件的过程及碰到的坑。
1. maven pom.xml 配置(只列出需要用到的2个核心依赖库)
<!-- jdbc driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
引用的第一个包是连数据库的驱动类,这个按照连接的数据库不同替换为对应的配置即可
引用的第二个包是生成mybatis相关文件需要用到的核心包,本文的主角就是它了
2. 写一个配置文件,用于由表生成我们需要的文件: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="MySqlTables" targetRuntime="MyBatis3">
<commentGenerator>
<!--是否去除自动生成的注释 true:是; false:否-->
<property name="suppressAllComments" value="false" />
</commentGenerator>
<!--数据库连接信息:驱动类、链接地址、用户名、密码 -->
<jdbcConnection driverClass="org.postgresql.Driver"
connectionURL="jdbc:postgresql://192.168.1.252:5432/mydb?characterEncoding=utf-8"
userId="postgres" password="postgres">
</jdbcConnection>
<javaTypeResolver>
<!--类型解析器-->
<!-- 默认false,把jdbc decimal 和 numeric 类型解析为integer -->
<!-- true,把jdbc decimal 和 numeric 类型解析为java.math.bigdecimal-->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成实体类及Example类的包名和位置-->
<javaModelGenerator targetPackage="com.study.mybatis.entity"
targetProject="src/main/java">
<!-- 是否让schema作为包后缀-->
<property name="enableSubPackages" value="true" />
<!-- 从数据库返回的值被清理前后的空格-->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件xml的包名和位置-->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<!-- 是否让schema作为包后缀-->
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成Dao接口的包名和位置-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.study.mybatis.dao"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 用于自动生成代码的数据库表;生成哪些表-->
<table tableName="core_container">
<generatedKey column="container_id" sqlStatement="postgresql" identity="true"/>
</table>
</context>
</generatorConfiguration>
3. 写一个main类,放在src/main/java下,比如 Main
import org.mybatis.generator.api.ShellRunner;
public class Main {
public static void main(String[] args) {
args = new String[] { "-configfile", "src\\main\\resources\\mybatis-generator.xml", "-overwrite" };
ShellRunner.main(args);
}
}
4. 在eclipse中运行上面的Main
5. 执行完毕,会生成四个文件:CoreContainer、CoreContainerExample、CoreContainerMapper、CoreContainerMapper.xml
CoreContainer(只列了部分字段):
public class CoreContainer {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column core_container.container_id
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
private String containerId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column core_container.container_no
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
private String containerNo;
}
CoreContainerExample(生成的example文件内容很长,下面只截取了部分片段):
package com.thingple.basf.report.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class CoreContainerExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table core_container
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table core_container
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
protected boolean distinct;
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
CoreContainerMapper(mapper接口也只截取了部分片段):
public interface CoreContainerMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table core_container
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
long countByExample(CoreContainerExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table core_container
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
int deleteByExample(CoreContainerExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table core_container
*
* @mbg.generated Sat Jul 11 16:29:50 CST 2020
*/
int deleteByPrimaryKey(String containerId);
}
CoreContainerMapper.xml(也只截取了部分片段):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thingple.basf.report.dao.CoreContainerMapper">
<resultMap id="BaseResultMap" type="com.thingple.basf.report.entity.CoreContainer">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Jul 11 16:25:06 CST 2020.
-->
<id column="container_id" jdbcType="VARCHAR" property="containerId" />
<result column="container_no" jdbcType="VARCHAR" property="containerNo" />
<result column="container_type" jdbcType="INTEGER" property="containerType" />
</resultMap>
<select id="selectByExample" parameterType="com.thingple.basf.report.entity.CoreContainerExample" resultMap="BaseResultMap">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Sat Jul 11 16:25:06 CST 2020.
-->
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from core_container
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
</mapper>
大功告成。怎么样,是否轻轻松松就由数据库表生成了所需要的mybatis相关文件?
遇到的坑:
写好配置文件mybatis-generator.xml后,始终过不了,有个红x提示配置文件有问题,执行Mian也会报错:The content of element type "context" must match
原因:
我将配置文件中context节点下sqlMapGenerator放置到javaClientGenerator后面了,即顺序不对。这个必须按照schema中定义的顺序排列context各子节点。