MyBatis Generator系列之七:不同目标运行时(Target Runtime)代码生成和基本使用

MyBatis Generator 专栏收录该内容
7 篇文章 0 订阅

不同目标运行时代码生成和基本使用


MyBatis Generator(MBG)根据其配置方式生成不同样式的代码。这是通过在 <context>配置元素上指定 targetRuntime属性来控制的

本次代码生成是通过Maven plugin运行MyBatis Generator(MBG),该方式的使用参考本系列其他文章

不同目标运行时对比

Target Runtime说明
MyBatis3DynamicSql默认值
生成java代码
不生成XML-仅用MyBatis3注解
生成的模型对象是“平面”的-没有单独的主键对象
生成的代码依赖于MyBatis动态SQL库
生成的代码量相对较小
生成的代码为查询构造提供了极大的灵活性
MyBatis3Kotlin生成Kotlin代码
不生成XML-仅用MyBatis3注解
生成的模型对象是“平面”的-没有单独的主键对象
生成的代码依赖于MyBatis动态SQL库
生成的代码量相对较小
生成的代码为查询构造提供了极大的灵活性
MyBatis3这是最初的运行时。在MBG 1.3.6版之前,MBG的大多数用法都使用这种样式的代码。
生成Java代码
生成没有XML的MyBatis3兼容的带注解的接口或者生成MyBatis3 兼容的XML
生成的模型对象可能具有一个层次结构,其中包含单独的主键对象和/或带有BLOB字段的单独对象
生成的代码没有外部依赖关系
生成的代码量非常大
生成的代码具有有限的查询构造功能,并且难以扩展
MyBatis3Simple这是MyBatis3运行时的简化版本。
生成Java代码
生成没有XML的MyBatis3兼容的带注解的接口或者生成MyBatis3 兼容的XML
生成的模型对象是“平面”的-没有单独的主键对象
生成的代码没有外部依赖关系
生成的代码量相对较小
没有生成“by example”或“selective”的方法
生成的代码不包含用于动态查询构造的方法,并且很难扩展

准备数据表

oa_staff

CREATE TABLE `oa_staff` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL COMMENT '名字',
  `gender` tinyint(4) NOT NULL DEFAULT '0' COMMENT '性别:0->男,1->女',
  `birthday` date DEFAULT NULL,
  `address` varchar(80) DEFAULT NULL COMMENT '住址',
  `native_place` varchar(80) DEFAULT NULL COMMENT '籍贯',
  `hiredate` date DEFAULT NULL COMMENT '入职日期',
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='员工信息'

MyBatis3DynamicSql

这个是默认的配置值

generatorConfig.xml

src\main\resources\generatorConfig.xml

<!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="dsql" targetRuntime="MyBatis3DynamicSql">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"
                        userId="root" password="123456"/>

        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <table tableName="oa_staff">
            <generatedKey column="id" sqlStatement="MySql" />
        </table>

    </context>
</generatorConfiguration>

关键:<context id="dsql" targetRuntime="MyBatis3DynamicSql">

生成产物

1、与表结构匹配的Java类

package com.example.model;

import java.util.Date;
import javax.annotation.Generated;

public class OaStaff {
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.044+08:00", comments="Source field: oa_staff.id")
    private Long id;

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.047+08:00", comments="Source field: oa_staff.name")
    private String name;

    .
    .
    .
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.047+08:00", comments="Source field: oa_staff.hiredate")
    public Date getHiredate() {
        return hiredate;
    }
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.048+08:00", comments="Source field: oa_staff.gmt_modified")
    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }
}

省略大部分生成的代码

2、用于启用动态选择、更新和删除的类

package com.example.mapper;

import java.sql.JDBCType;
import java.util.Date;
import javax.annotation.Generated;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;

public final class OaStaffDynamicSqlSupport {
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.05+08:00", comments="Source Table: oa_staff")
    public static final OaStaff oaStaff = new OaStaff();

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.051+08:00", comments="Source field: oa_staff.id")
    public static final SqlColumn<Long> id = oaStaff.id;

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.051+08:00", comments="Source field: oa_staff.name")
    public static final SqlColumn<String> name = oaStaff.name;

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.051+08:00", comments="Source field: oa_staff.gender")
    public static final SqlColumn<Byte> gender = oaStaff.gender;
    .
    .
    .
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.052+08:00", comments="Source field: oa_staff.gmt_create")
    public static final SqlColumn<Date> gmtCreate = oaStaff.gmtCreate;

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.052+08:00", comments="Source field: oa_staff.gmt_modified")
    public static final SqlColumn<Date> gmtModified = oaStaff.gmtModified;

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.051+08:00", comments="Source Table: oa_staff")
    public static final class OaStaff extends SqlTable {
        public final SqlColumn<Long> id = column("id", JDBCType.BIGINT);

        public final SqlColumn<String> name = column("name", JDBCType.VARCHAR);

        public final SqlColumn<Byte> gender = column("gender", JDBCType.TINYINT);

        public final SqlColumn<Date> birthday = column("birthday", JDBCType.DATE);
    .
    .
    .
        public final SqlColumn<Date> gmtCreate = column("gmt_create", JDBCType.TIMESTAMP);

        public final SqlColumn<Date> gmtModified = column("gmt_modified", JDBCType.TIMESTAMP);

        public OaStaff() {
            super("oa_staff");
        }
    }
}

省略大部分生成的代码

3、Java映射器接口

package com.example.mapper;

import static com.example.mapper.OaStaffDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;

import com.example.model.OaStaff;
import java.util.List;
import java.util.Optional;
import javax.annotation.Generated;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
.
.
.
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.dynamic.sql.BasicColumn;
.
.
.
import org.mybatis.dynamic.sql.update.UpdateDSLCompleter;
import org.mybatis.dynamic.sql.update.UpdateModel;
import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider;
import org.mybatis.dynamic.sql.util.SqlProviderAdapter;
import org.mybatis.dynamic.sql.util.mybatis3.MyBatis3Utils;

@Mapper
public interface OaStaffMapper {
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.06+08:00", comments="Source Table: oa_staff")
    BasicColumn[] selectList = BasicColumn.columnList(id, name, gender, birthday, address, nativePlace, hiredate, gmtCreate, gmtModified);

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.052+08:00", comments="Source Table: oa_staff")
    @SelectProvider(type=SqlProviderAdapter.class, method="select")
    long count(SelectStatementProvider selectStatement);

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.053+08:00", comments="Source Table: oa_staff")
    @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
    int delete(DeleteStatementProvider deleteStatement);
.
.
.
    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.057+08:00", comments="Source Table: oa_staff")
    @UpdateProvider(type=SqlProviderAdapter.class, method="update")
    int update(UpdateStatementProvider updateStatement);

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.057+08:00", comments="Source Table: oa_staff")
    default long count(CountDSLCompleter completer) {
        return MyBatis3Utils.countFrom(this::count, oaStaff, completer);
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.057+08:00", comments="Source Table: oa_staff")
    default int delete(DeleteDSLCompleter completer) {
        return MyBatis3Utils.deleteFrom(this::delete, oaStaff, completer);
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.058+08:00", comments="Source Table: oa_staff")
    default int deleteByPrimaryKey(Long id_) {
        return delete(c -> 
            c.where(id, isEqualTo(id_))
        );
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.058+08:00", comments="Source Table: oa_staff")
    default int insert(OaStaff record) {
        return MyBatis3Utils.insert(this::insert, record, oaStaff, c ->
            c.map(id).toProperty("id")
            .map(name).toProperty("name")
            .map(gender).toProperty("gender")
            .map(birthday).toProperty("birthday")
            .map(address).toProperty("address")
            .map(nativePlace).toProperty("nativePlace")
            .map(hiredate).toProperty("hiredate")
            .map(gmtCreate).toProperty("gmtCreate")
            .map(gmtModified).toProperty("gmtModified")
        );
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.059+08:00", comments="Source Table: oa_staff")
    default int insertSelective(OaStaff record) {
        return MyBatis3Utils.insert(this::insert, record, oaStaff, c ->
            c.map(id).toProperty("id")
            .map(name).toPropertyWhenPresent("name", record::getName)
            .map(gender).toPropertyWhenPresent("gender", record::getGender)
            .map(birthday).toPropertyWhenPresent("birthday", record::getBirthday)
            .map(address).toPropertyWhenPresent("address", record::getAddress)
            .map(nativePlace).toPropertyWhenPresent("nativePlace", record::getNativePlace)
            .map(hiredate).toPropertyWhenPresent("hiredate", record::getHiredate)
            .map(gmtCreate).toPropertyWhenPresent("gmtCreate", record::getGmtCreate)
            .map(gmtModified).toPropertyWhenPresent("gmtModified", record::getGmtModified)
        );
    }

   .
   .
   .

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.062+08:00", comments="Source Table: oa_staff")
    default Optional<OaStaff> selectByPrimaryKey(Long id_) {
        return selectOne(c ->
            c.where(id, isEqualTo(id_))
        );
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.062+08:00", comments="Source Table: oa_staff")
    default int update(UpdateDSLCompleter completer) {
        return MyBatis3Utils.update(this::update, oaStaff, completer);
    }

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.062+08:00", comments="Source Table: oa_staff")
    static UpdateDSL<UpdateModel> updateAllColumns(OaStaff record, UpdateDSL<UpdateModel> dsl) {
        return dsl.set(id).equalTo(record::getId)
                .set(name).equalTo(record::getName)
                .set(gender).equalTo(record::getGender)
                .set(birthday).equalTo(record::getBirthday)
                .set(address).equalTo(record::getAddress)
                .set(nativePlace).equalTo(record::getNativePlace)
                .set(hiredate).equalTo(record::getHiredate)
                .set(gmtCreate).equalTo(record::getGmtCreate)
                .set(gmtModified).equalTo(record::getGmtModified);
    }

.
.
.

    @Generated(value="org.mybatis.generator.api.MyBatisGenerator", date="2020-05-03T21:35:35.064+08:00", comments="Source Table: oa_staff")
    default int updateByPrimaryKeySelective(OaStaff record) {
        return update(c ->
            c.set(name).equalToWhenPresent(record::getName)
            .set(gender).equalToWhenPresent(record::getGender)
            .set(birthday).equalToWhenPresent(record::getBirthday)
            .set(address).equalToWhenPresent(record::getAddress)
            .set(nativePlace).equalToWhenPresent(record::getNativePlace)
            .set(hiredate).equalToWhenPresent(record::getHiredate)
            .set(gmtCreate).equalToWhenPresent(record::getGmtCreate)
            .set(gmtModified).equalToWhenPresent(record::getGmtModified)
            .where(id, isEqualTo(record::getId))
        );
    }
}

省略大部分生成的代码

测试生成代码

package com.example;

import com.example.mapper.OaStaffMapper;
import com.example.model.OaStaff;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;

import static com.example.mapper.OaStaffDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;

public class OaStaffTableTest {
    private final Logger log = LoggerFactory.getLogger(OaStaffTableTest.class);
    static SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private OaStaffMapper oaStaffMapper;

    @Before
    public void init() throws IOException {
        String resource = "MapperConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        oaStaffMapper = sqlSession.getMapper(OaStaffMapper.class);
    }

    @Test
    public void testInsert() {
        OaStaff oaStaff = new OaStaff();
        oaStaff.setName("lisi");
        oaStaff.setGender(Byte.parseByte("0"));
        oaStaffMapper.insert(oaStaff);
        sqlSession.commit();
    }

    @Test
    public void testSelect() {
        Optional<OaStaff> oaStaffOptional = oaStaffMapper.selectByPrimaryKey(1L);
        OaStaff staff = oaStaffOptional.get();
        log.info("id = {}, name= {}, addr = {}", staff.getId(), staff.getName(), staff.getAddress());
        List<OaStaff> select = oaStaffMapper.select(c -> c.where(id, isEqualTo(1L)));
        for (OaStaff s : select) {
            log.info("name={}, id = {}, addr = {}", s.getName(), s.getId(), s.getAddress());
        }
    }

    @Test
    public void testUpdate() {
        Optional<OaStaff> oaStaffOptional = oaStaffMapper.selectByPrimaryKey(1L);
        OaStaff oaStaff = oaStaffOptional.get();
        oaStaff.setAddress("北京市海淀区");
        oaStaffMapper.updateByPrimaryKey(oaStaff);
        oaStaffMapper.update(c -> c.set(address).equalTo("北京市朝阳区")
                .set(gender).equalTo(Byte.parseByte("1"))
                .where(id, isEqualTo(2L)));
        sqlSession.commit();
    }

    @Test
    public void testDelete() {
        oaStaffMapper.deleteByPrimaryKey(40L);
        oaStaffMapper.delete(c -> c.where(name, isEqualTo("libiao"), and(gender, isEqualTo(Byte.parseByte("1")))).or(address, isEqualTo("广州市")));
    }
    @After
    public void destroy() {
        sqlSession.close();
    }

}

MapperConfig.xml内容

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.example.mapper"/>
    </mappers>
</configuration>

MyBatis3Kotlin

由于本人工作用没有用到Kotlin语言,生成适用于Kotlin的部分略过。

MyBatis3

generatorConfig.xml

src\main\resources\generatorConfig.xml

<!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="myBatis3" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"
                        userId="root" password="123456"/>

        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <table tableName="oa_staff">
            <generatedKey column="id" sqlStatement="MySql" />
        </table>
    </context>
</generatorConfiguration>

生成产物

1、与表结构匹配的Java类

package com.example.model;

import java.util.Date;

public class OaStaff {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.id
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    private Long id;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.name
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    private String name;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.gender
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    private Byte gender;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.birthday
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    private Date birthday;

.
.
.

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column oa_staff.gmt_create
     *
     * @param gmtCreate the value for oa_staff.gmt_create
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column oa_staff.gmt_modified
     *
     * @return the value of oa_staff.gmt_modified
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public Date getGmtModified() {
        return gmtModified;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column oa_staff.gmt_modified
     *
     * @param gmtModified the value for oa_staff.gmt_modified
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }
}

省略大部分生成的代码

2、用于启用动态选择、更新和删除的类(Example

package com.example.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class OaStaffExample {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    protected String orderByClause;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    protected boolean distinct;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    protected List<Criteria> oredCriteria;

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public OaStaffExample() {
        oredCriteria = new ArrayList<>();
    }
.
.
.
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<>();
        }

        .
        .
        .

        public Criteria andGmtModifiedNotBetween(Date value1, Date value2) {
            addCriterion("gmt_modified not between", value1, value2, "gmtModified");
            return (Criteria) this;
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table oa_staff
     *
     * @mbg.generated do_not_delete_during_merge Sun May 03 22:55:28 CST 2020
     */
    public static class Criteria extends GeneratedCriteria {
        protected Criteria() {
            super();
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;
.
.
.

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

省略大部分生成的代码

3、Java映射器接口

package com.example.mapper;

import com.example.model.OaStaff;
import com.example.model.OaStaffExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface OaStaffMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    long countByExample(OaStaffExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    int deleteByExample(OaStaffExample example);

.
.
.
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    int updateByPrimaryKeySelective(OaStaff record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 22:55:28 CST 2020
     */
    int updateByPrimaryKey(OaStaff record);
}

省略大部分生成的代码

4、与MyBatis3兼容的SQL映射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.example.mapper.OaStaffMapper">
  <resultMap id="BaseResultMap" type="com.example.model.OaStaff">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 22:55:28 CST 2020.
    -->
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="gender" jdbcType="TINYINT" property="gender" />
    <result column="birthday" jdbcType="DATE" property="birthday" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="native_place" jdbcType="VARCHAR" property="nativePlace" />
    <result column="hiredate" jdbcType="DATE" property="hiredate" />
    <result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate" />
    <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 22:55:28 CST 2020.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  .
  .
  .
  <update id="updateByPrimaryKey" parameterType="com.example.model.OaStaff">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 22:55:28 CST 2020.
    -->
    update oa_staff
    set name = #{name,jdbcType=VARCHAR},
      gender = #{gender,jdbcType=TINYINT},
      birthday = #{birthday,jdbcType=DATE},
      address = #{address,jdbcType=VARCHAR},
      native_place = #{nativePlace,jdbcType=VARCHAR},
      hiredate = #{hiredate,jdbcType=DATE},
      gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
      gmt_modified = #{gmtModified,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

省略大部分生成的代码

测试生成代码

package com.example;

import com.example.mapper.OaStaffMapper;
import com.example.model.OaStaff;
import com.example.model.OaStaffExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class OaStaffTableTest {
    static final Logger log = LoggerFactory.getLogger(OaStaffTableTest.class);
    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;
    OaStaffMapper oaStaffMapper;
    @Before
    public void init() throws IOException {
        String resource = "MapperConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        oaStaffMapper = sqlSession.getMapper(OaStaffMapper.class);
    }

    @Test
    public void testInsert() {
        OaStaff staff = new OaStaff();
        staff.setName("张三");
        staff.setAddress("火星");
        staff.setGender(new Byte("1"));
        Date now = new Date();
        staff.setGmtCreate(now);
        staff.setGmtModified(now);
        oaStaffMapper.insert(staff);
        sqlSession.commit();
    }

    @Test
    public void testSelect() {
        OaStaff staff = oaStaffMapper.selectByPrimaryKey(3L);
        log.info("id = {}, name={} addr= {}, create= {}", staff.getId(), staff.getName(), staff.getAddress(), staff.getGmtCreate());
        OaStaffExample example = new OaStaffExample();
        example.or()
                .andNameLike("l%");
        List<OaStaff> oaStaffs = oaStaffMapper.selectByExample(example);
        for (OaStaff s : oaStaffs) {
            log.info("id = {}, name={} addr= {}, create= {}", s.getId(), s.getName(), s.getAddress(), s.getGmtCreate());
        }
    }

    @Test
    public void testUpdate() {
        OaStaff staff = oaStaffMapper.selectByPrimaryKey(3L);
        Date now = new Date();
        staff.setGmtModified(now);
//        oaStaffMapper.updateByPrimaryKey(staff); // ok

        OaStaffExample example = new OaStaffExample();
        example.or()
                .andNameLike("l%");
        OaStaff s = new OaStaff();
        s.setAddress("第七区");
//        oaStaffMapper.updateByExample(s, example); // error! 所有字段全部更新,而s.id为空,主键不允许为空导致更新失败
        oaStaffMapper.updateByExampleSelective(s, example); // ok 只更更新 s 中不为空的字段
    }

    @Test
    public void testDelete() {
        oaStaffMapper.deleteByPrimaryKey(390L);
        OaStaffExample example = new OaStaffExample();
        example.or()
                .andNameLike("l%");
        oaStaffMapper.deleteByExample(example);
    }
    @After
    public void destroy() {
        sqlSession.close();
    }

}

MapperConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.example.mapper"/>
    </mappers>
</configuration>

MyBatis3Simple

generatorConfig.xml

src\main\resources\generatorConfig.xml

<!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="simple" targetRuntime="MyBatis3Simple">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"
                        userId="root" password="123456"/>

        <javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>

        <sqlMapGenerator targetPackage="com.example.mapper" targetProject="src/main/resources"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>

        <table tableName="oa_staff">
            <generatedKey column="id" sqlStatement="MySql" />
        </table>
    </context>
</generatorConfiguration>

生成产物

1、与表结构匹配的Java类

package com.example.model;

import java.util.Date;

public class OaStaff {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.id
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Long id;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.name
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private String name;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.gender
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Byte gender;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.birthday
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Date birthday;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.address
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private String address;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.native_place
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private String nativePlace;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.hiredate
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Date hiredate;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.gmt_create
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Date gmtCreate;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column oa_staff.gmt_modified
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    private Date gmtModified;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column oa_staff.id
     *
     * @return the value of oa_staff.id
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    public Long getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column oa_staff.id
     *
     * @param id the value for oa_staff.id
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column oa_staff.name
     *
     * @return the value of oa_staff.name
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    public String getName() {
        return name;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column oa_staff.name
     *
     * @param name the value for oa_staff.name
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    public void setName(String name) {
        this.name = name;
    }

.
.
.

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column oa_staff.gmt_modified
     *
     * @param gmtModified the value for oa_staff.gmt_modified
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }
}

省略大部分生成的代码

2、Java映射器接口

package com.example.mapper;

import com.example.model.OaStaff;
import java.util.List;

public interface OaStaffMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    int deleteByPrimaryKey(Long id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    int insert(OaStaff record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    OaStaff selectByPrimaryKey(Long id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    List<OaStaff> selectAll();

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table oa_staff
     *
     * @mbg.generated Sun May 03 23:34:18 CST 2020
     */
    int updateByPrimaryKey(OaStaff record);
}

3、与MyBatis3兼容的SQL映射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.example.mapper.OaStaffMapper">
  <resultMap id="BaseResultMap" type="com.example.model.OaStaff">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="gender" jdbcType="TINYINT" property="gender" />
    <result column="birthday" jdbcType="DATE" property="birthday" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="native_place" jdbcType="VARCHAR" property="nativePlace" />
    <result column="hiredate" jdbcType="DATE" property="hiredate" />
    <result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate" />
    <result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    delete from oa_staff
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.example.model.OaStaff">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.Long">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into oa_staff (id, name, gender, 
      birthday, address, native_place, 
      hiredate, gmt_create, gmt_modified
      )
    values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{gender,jdbcType=TINYINT}, 
      #{birthday,jdbcType=DATE}, #{address,jdbcType=VARCHAR}, #{nativePlace,jdbcType=VARCHAR}, 
      #{hiredate,jdbcType=DATE}, #{gmtCreate,jdbcType=TIMESTAMP}, #{gmtModified,jdbcType=TIMESTAMP}
      )
  </insert>
  <update id="updateByPrimaryKey" parameterType="com.example.model.OaStaff">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    update oa_staff
    set name = #{name,jdbcType=VARCHAR},
      gender = #{gender,jdbcType=TINYINT},
      birthday = #{birthday,jdbcType=DATE},
      address = #{address,jdbcType=VARCHAR},
      native_place = #{nativePlace,jdbcType=VARCHAR},
      hiredate = #{hiredate,jdbcType=DATE},
      gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
      gmt_modified = #{gmtModified,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    select id, name, gender, birthday, address, native_place, hiredate, gmt_create, gmt_modified
    from oa_staff
    where id = #{id,jdbcType=BIGINT}
  </select>
  <select id="selectAll" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun May 03 23:34:18 CST 2020.
    -->
    select id, name, gender, birthday, address, native_place, hiredate, gmt_create, gmt_modified
    from oa_staff
  </select>
</mapper>

测试生成代码

package com.example;

import com.example.mapper.OaStaffMapper;
import com.example.model.OaStaff;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class OaStaffTableTest {
    private static final Logger log = LoggerFactory.getLogger(OaStaffTableTest.class);
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private OaStaffMapper oaStaffMapper;
    @Before
    public void init() throws IOException {
        String resource = "MapperConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        oaStaffMapper = sqlSession.getMapper(OaStaffMapper.class);
    }

    @Test
    public void testInsert() {
        OaStaff staff = new OaStaff();
        staff.setName("赵武");
        staff.setAddress("月球");
        staff.setGender(Byte.valueOf("1"));
        Date now = new Date();
        staff.setGmtCreate(now);
        staff.setGmtModified(now);
        oaStaffMapper.insert(staff);
        sqlSession.commit();
    }

    @Test
    public void testSelect() {
        OaStaff staff = oaStaffMapper.selectByPrimaryKey(4L);
        log.info("id = {}, name={} addr= {}, create= {}", staff.getId(), staff.getName(), staff.getAddress(), staff.getGmtCreate());

    }

    @Test
    public void testUpdate() {
        OaStaff staff = oaStaffMapper.selectByPrimaryKey(4L);
        Date now = new Date();
        staff.setGmtModified(now);
        oaStaffMapper.updateByPrimaryKey(staff);
    }

    @Test
    public void testDelete() {
        oaStaffMapper.deleteByPrimaryKey(390L);
    }
    @After
    public void destroy() {
        sqlSession.close();
    }

}

MapperConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.56.101:3306/db_example?characterEncoding=utf8&amp;autoReconnect=true&amp;serverTimezone=PRC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.example.mapper"/>
    </mappers>
</configuration>

完整代码

https://gitee.com/tobybiao/MBG-examples

参考

MyBatis Generator Quick Start Guide

  • 2
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值