Mybatis自动生成mapper、实体类及mapper xml文件

    项目中用的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各子节点。

MyBatis是一款流行的Java持久化框架,它提供了许多便捷的功能来简化数据库操作。其中一个重要的功能是自动生成MapperMyBatis自动生成Mapper是通过读取数据库表结构和配置文件,生成对应的Mapper接口和XML映射文件。这样我们就可以通过调用生成的Mapper接口来执行数据库的增删改查操作,而无需手动编写SQL语句。 使用MyBatis自动生成Mapper的步骤如下: 1. 首先,在MyBatis的配置文件中配置数据源和其他的一些相关信息。 2. 创建一个Java类,用来配置自动生成Mapper的参数,如数据库表名、实体类名、Mapper接口包名等。 3. 在配置文件中引入自动生成Mapper的插件。 4. 运行MyBatis自动生成Mapper插件,将会根据配置生成Mapper接口和XML映射文件。 生成的Mapper接口可以直接调用,以执行对应的数据库操作。例如,我们可以通过调用insert()方法来插入一条记录,或者通过调用selectById()方法来根据ID查询一条记录。 通过使用MyBatis自动生成Mapper,我们可以减少手动编写SQL语句的工作量,提高开发效率。同时,由于MyBatis是基于XML配置的,我们也可以根据需要对生成的XML映射文件进行修改和优化。 总结起来,MyBatis自动生成Mapper是一种方便快捷的工具,它可以根据数据库的表结构自动生成对应的Mapper接口和XML映射文件,进一步简化了数据库操作的开发工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值