mybatis-generator 逆向生成工具(实体、dao、sql)

介绍:
mybatis-generator 是一个逆向生成工具,用于将数据库表逆向生成实体对象(entity)持久层Dao接口以及用于操作数据库的sql语句xml文件。对于简单的单表操作,增删改查几乎不用动手写任额外的代码。因为这些都已经通过逆向工程自动生成了,所以帮我们省了一大摊子事儿。

项目结构如下:

下面简单介绍其使用和配置方式:

数据库连接配置:

jdbc.driverLocation=tool/mysql-connector-java-5.1.12.jar
jdbc.driverClassName=com.mysql.jdbc.Driver
#测试环境
jdbc.url=jdbc:mysql://10.0.2.30:3306/xsignal2_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=true&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=cloud2

逆向生成相关配置:

<?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>
    <!--导入属性配置 -->
    <properties resource="generator.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置 -->
    <!--<classPathEntry location="tool/mysql-connector-java-5.1.12.jar"/>-->
    <classPathEntry location="${jdbc.driverLocation}"/>

    <context id="default" targetRuntime="MyBatis3">
        <!--toString方法插件-->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!--序列化插件-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!--生成equals方法插件-->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
        <!--替换后缀插件,Mapper替换为dao-->
        <!--<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
            <property name="searchString" value="$Mapper"/>
            <property name="replaceString"
                      value="Dao"/>
        </plugin>-->

        <!--分页插件-->
        <plugin type="com.xiaofeng.generator.plugin.ModelExampleLimitPlugin"/>

        <commentGenerator type="com.xiaofeng.generator.plugin.CommentGenerator">
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <!--<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://10.0.2.30:3306/xsignal2_test"
                        userId="root"
                        password="cloud2">
        </jdbcConnection>-->

        <!-- 数据库连接 -->
        <jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}"/>

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->

        <javaModelGenerator targetPackage="com.xiaofeng.generator.model"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <sqlMapGenerator targetPackage="sqlmap"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->

        <javaClientGenerator targetPackage="com.xiaofeng.generator.mapper"
                             targetProject="src/main/java" type="XMLMAPPER"><!-- XMLMAPPER,SPRING -->
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--此处设置需要生成的表-->
        <table tableName="tb_company_activity_info"
               domainObjectName="CompanyActivityInfo">
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

实体注释插件:

package com.xiaofeng.generator.plugin;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;

/**
 * @author xiaofeng
 * @version V1.0
 * @title: CommentGenerator
 * @package: com.xiaofeng.generator.plugin
 * @description: 生成model中,字段增加注释
 * @date 2019/9/11 18:07
 */
public class CommentGenerator extends DefaultCommentGenerator {

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
        super.addFieldComment(field, introspectedTable, introspectedColumn);
        if (introspectedColumn.getRemarks() != null && !introspectedColumn.getRemarks().equals("")) {
            field.addJavaDocLine("/**");
            field.addJavaDocLine(" * " + introspectedColumn.getRemarks());
            addJavadocTag(field, false);
            field.addJavaDocLine(" */");
        }
    }

}

分页相关插件:

package com.xiaofeng.generator.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.ShellRunner;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.util.List;

public class ModelExampleLimitPlugin extends PluginAdapter {

	private String limitTypeString = "com.xiaofeng.generator.plugin.Limit";
	@Override
	public boolean validate(List<String> arg0) {
		return true;
	}

	@Override
	public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		FullyQualifiedJavaType limitType = new FullyQualifiedJavaType(limitTypeString);
		topLevelClass.addImportedType(limitType);

		Field field = new Field();
		field.setName("limit");
		field.setType(limitType);
		field.setVisibility(JavaVisibility.PRIVATE);
		topLevelClass.addField(field);

		Method setMethod = new Method();
		setMethod.setName("setLimit");
		setMethod.setVisibility(JavaVisibility.PUBLIC);
		setMethod.addParameter(new Parameter(limitType, "limit"));
		setMethod.addBodyLine("this.limit = limit;");
		topLevelClass.addMethod(setMethod);

		Method getMethod = new Method();
		getMethod.setName("getLimit");
		getMethod.setVisibility(JavaVisibility.PUBLIC);
		getMethod.setReturnType(limitType);
		getMethod.addBodyLine("return this.limit;");
		topLevelClass.addMethod(getMethod);

		return true;
	}

	@Override
	public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
			IntrospectedTable introspectedTable) {
		addLimitSqlMapCode(element);
		return true;
	}

	@Override
	public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,
			IntrospectedTable introspectedTable) {
		List<Element> elementList = element.getElements();
		XmlElement orderByElement = (XmlElement) elementList.get(elementList.size() - 1);
		orderByElement.getElements().set(0, new TextElement("order by ${orderByClause}"));
		addLimitSqlMapCode(element);
		return true;
	}

	private void addLimitSqlMapCode(XmlElement element) {
		XmlElement limit = new XmlElement("if");
		limit.addAttribute(new Attribute("test", "limit != null"));
		limit.addElement(new TextElement("limit #{limit.start},#{limit.maxRows}"));
		element.addElement(limit);
	}
	
	public static void main(String[] args) {
		 String config= ModelExampleLimitPlugin.class.getClassLoader().getResource("/tool/generatorConfig.xml").getFile();

         String[] arg= { "-configfile", config, "-overwrite"};

         ShellRunner.main(arg);
	}
}
package com.xiaofeng.generator.plugin;

public class Limit {

	private int start = 0;
	private int maxRows = -1;

	public Limit(int start) {
		this.start = start;
	}

	public Limit(int start, int maxRows) {
		this.start = start;
		this.maxRows = maxRows;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getMaxRows() {
		return maxRows;
	}

	public void setMaxRows(int maxRows) {
		this.maxRows = maxRows;
	}

}

执行命令生成:

clean install mybatis-generator:generate -e

生成后的效果如图(包含实体类,Mapper(dao)接口,xml文件(封装sql语句)):

生成的实体类如下:

package com.xiaofeng.generator.model;

import java.io.Serializable;
import java.util.Date;

public class CompanyActivityInfo implements Serializable {
    /**
     * 活动ID
     *
     * @mbg.generated
     */
    private Long id;

    /**
     * 企业ID
     *
     * @mbg.generated
     */
    private Long companyId;

    /**
     * 活动类型
     *
     * @mbg.generated
     */
    private String activityType;

    /**
     * 活动名称
     *
     * @mbg.generated
     */
    private String activityName;

    /**
     * 报名开始时间
     *
     * @mbg.generated
     */
    private Date applyStartTime;

    /**
     * 报名结束时间
     *
     * @mbg.generated
     */
    private Date applyEndTime;

    /**
     * 比赛开始时间
     *
     * @mbg.generated
     */
    private Date competitionStartTime;

    /**
     * 比赛结束时间
     *
     * @mbg.generated
     */
    private Date competitionEndTime;

    /**
     * 0未发布 1未开始 2进行中 3已结束
     *
     * @mbg.generated
     */
    private Byte status;

    /**
     * 报名人数
     *
     * @mbg.generated
     */
    private Long applicant;

    /**
     * 参赛人数
     *
     * @mbg.generated
     */
    private Long participant;

    /**
     * 虚拟人数
     *
     * @mbg.generated
     */
    private Long virtual;

    /**
     * 1展示 0隐藏
     *
     * @mbg.generated
     */
    private Byte isShow;

    /**
     * 限制人数 -1不限制
     *
     * @mbg.generated
     */
    private Long maxPlayers;

    /**
     * 背景图
     *
     * @mbg.generated
     */
    private String backdrop;

    /**
     * 活动链接
     *
     * @mbg.generated
     */
    private String activityLink;

    /**
     * 风险及免责条款
     *
     * @mbg.generated
     */
    private String riskAndDisclaimer;

    /**
     * 创建人
     *
     * @mbg.generated
     */
    private String createBy;

    /**
     * 创建时间
     *
     * @mbg.generated
     */
    private Date createTime;

    /**
     * 修改人
     *
     * @mbg.generated
     */
    private String updateBy;

    /**
     * 修改时间
     *
     * @mbg.generated
     */
    private Date updateTime;

    /**
     * 0未删除 1已删除
     *
     * @mbg.generated
     */
    private Byte remove;

    /**
     * 展示字段(逗号隔开)
     *
     * @mbg.generated
     */
    private String viewField;

    /**
     * 比赛须知
     *
     * @mbg.generated
     */
    private String competitionNotice;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getCompanyId() {
        return companyId;
    }

    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }

    public String getActivityType() {
        return activityType;
    }

    public void setActivityType(String activityType) {
        this.activityType = activityType == null ? null : activityType.trim();
    }

    public String getActivityName() {
        return activityName;
    }

    public void setActivityName(String activityName) {
        this.activityName = activityName == null ? null : activityName.trim();
    }

    public Date getApplyStartTime() {
        return applyStartTime;
    }

    public void setApplyStartTime(Date applyStartTime) {
        this.applyStartTime = applyStartTime;
    }

    public Date getApplyEndTime() {
        return applyEndTime;
    }

    public void setApplyEndTime(Date applyEndTime) {
        this.applyEndTime = applyEndTime;
    }

    public Date getCompetitionStartTime() {
        return competitionStartTime;
    }

    public void setCompetitionStartTime(Date competitionStartTime) {
        this.competitionStartTime = competitionStartTime;
    }

    public Date getCompetitionEndTime() {
        return competitionEndTime;
    }

    public void setCompetitionEndTime(Date competitionEndTime) {
        this.competitionEndTime = competitionEndTime;
    }

    public Byte getStatus() {
        return status;
    }

    public void setStatus(Byte status) {
        this.status = status;
    }

    public Long getApplicant() {
        return applicant;
    }

    public void setApplicant(Long applicant) {
        this.applicant = applicant;
    }

    public Long getParticipant() {
        return participant;
    }

    public void setParticipant(Long participant) {
        this.participant = participant;
    }

    public Long getVirtual() {
        return virtual;
    }

    public void setVirtual(Long virtual) {
        this.virtual = virtual;
    }

    public Byte getIsShow() {
        return isShow;
    }

    public void setIsShow(Byte isShow) {
        this.isShow = isShow;
    }

    public Long getMaxPlayers() {
        return maxPlayers;
    }

    public void setMaxPlayers(Long maxPlayers) {
        this.maxPlayers = maxPlayers;
    }

    public String getBackdrop() {
        return backdrop;
    }

    public void setBackdrop(String backdrop) {
        this.backdrop = backdrop == null ? null : backdrop.trim();
    }

    public String getActivityLink() {
        return activityLink;
    }

    public void setActivityLink(String activityLink) {
        this.activityLink = activityLink == null ? null : activityLink.trim();
    }

    public String getRiskAndDisclaimer() {
        return riskAndDisclaimer;
    }

    public void setRiskAndDisclaimer(String riskAndDisclaimer) {
        this.riskAndDisclaimer = riskAndDisclaimer == null ? null : riskAndDisclaimer.trim();
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy == null ? null : createBy.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy == null ? null : updateBy.trim();
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Byte getRemove() {
        return remove;
    }

    public void setRemove(Byte remove) {
        this.remove = remove;
    }

    public String getViewField() {
        return viewField;
    }

    public void setViewField(String viewField) {
        this.viewField = viewField == null ? null : viewField.trim();
    }

    public String getCompetitionNotice() {
        return competitionNotice;
    }

    public void setCompetitionNotice(String competitionNotice) {
        this.competitionNotice = competitionNotice == null ? null : competitionNotice.trim();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", companyId=").append(companyId);
        sb.append(", activityType=").append(activityType);
        sb.append(", activityName=").append(activityName);
        sb.append(", applyStartTime=").append(applyStartTime);
        sb.append(", applyEndTime=").append(applyEndTime);
        sb.append(", competitionStartTime=").append(competitionStartTime);
        sb.append(", competitionEndTime=").append(competitionEndTime);
        sb.append(", status=").append(status);
        sb.append(", applicant=").append(applicant);
        sb.append(", participant=").append(participant);
        sb.append(", virtual=").append(virtual);
        sb.append(", isShow=").append(isShow);
        sb.append(", maxPlayers=").append(maxPlayers);
        sb.append(", backdrop=").append(backdrop);
        sb.append(", activityLink=").append(activityLink);
        sb.append(", riskAndDisclaimer=").append(riskAndDisclaimer);
        sb.append(", createBy=").append(createBy);
        sb.append(", createTime=").append(createTime);
        sb.append(", updateBy=").append(updateBy);
        sb.append(", updateTime=").append(updateTime);
        sb.append(", remove=").append(remove);
        sb.append(", viewField=").append(viewField);
        sb.append(", competitionNotice=").append(competitionNotice);
        sb.append("]");
        return sb.toString();
    }

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        CompanyActivityInfo other = (CompanyActivityInfo) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getCompanyId() == null ? other.getCompanyId() == null : this.getCompanyId().equals(other.getCompanyId()))
            && (this.getActivityType() == null ? other.getActivityType() == null : this.getActivityType().equals(other.getActivityType()))
            && (this.getActivityName() == null ? other.getActivityName() == null : this.getActivityName().equals(other.getActivityName()))
            && (this.getApplyStartTime() == null ? other.getApplyStartTime() == null : this.getApplyStartTime().equals(other.getApplyStartTime()))
            && (this.getApplyEndTime() == null ? other.getApplyEndTime() == null : this.getApplyEndTime().equals(other.getApplyEndTime()))
            && (this.getCompetitionStartTime() == null ? other.getCompetitionStartTime() == null : this.getCompetitionStartTime().equals(other.getCompetitionStartTime()))
            && (this.getCompetitionEndTime() == null ? other.getCompetitionEndTime() == null : this.getCompetitionEndTime().equals(other.getCompetitionEndTime()))
            && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()))
            && (this.getApplicant() == null ? other.getApplicant() == null : this.getApplicant().equals(other.getApplicant()))
            && (this.getParticipant() == null ? other.getParticipant() == null : this.getParticipant().equals(other.getParticipant()))
            && (this.getVirtual() == null ? other.getVirtual() == null : this.getVirtual().equals(other.getVirtual()))
            && (this.getIsShow() == null ? other.getIsShow() == null : this.getIsShow().equals(other.getIsShow()))
            && (this.getMaxPlayers() == null ? other.getMaxPlayers() == null : this.getMaxPlayers().equals(other.getMaxPlayers()))
            && (this.getBackdrop() == null ? other.getBackdrop() == null : this.getBackdrop().equals(other.getBackdrop()))
            && (this.getActivityLink() == null ? other.getActivityLink() == null : this.getActivityLink().equals(other.getActivityLink()))
            && (this.getRiskAndDisclaimer() == null ? other.getRiskAndDisclaimer() == null : this.getRiskAndDisclaimer().equals(other.getRiskAndDisclaimer()))
            && (this.getCreateBy() == null ? other.getCreateBy() == null : this.getCreateBy().equals(other.getCreateBy()))
            && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
            && (this.getUpdateBy() == null ? other.getUpdateBy() == null : this.getUpdateBy().equals(other.getUpdateBy()))
            && (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime()))
            && (this.getRemove() == null ? other.getRemove() == null : this.getRemove().equals(other.getRemove()))
            && (this.getViewField() == null ? other.getViewField() == null : this.getViewField().equals(other.getViewField()))
            && (this.getCompetitionNotice() == null ? other.getCompetitionNotice() == null : this.getCompetitionNotice().equals(other.getCompetitionNotice()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getCompanyId() == null) ? 0 : getCompanyId().hashCode());
        result = prime * result + ((getActivityType() == null) ? 0 : getActivityType().hashCode());
        result = prime * result + ((getActivityName() == null) ? 0 : getActivityName().hashCode());
        result = prime * result + ((getApplyStartTime() == null) ? 0 : getApplyStartTime().hashCode());
        result = prime * result + ((
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值