Project sharing | use MyBatis Generator to automatically generate database mapping files

Keywords: Database Mybatis SQL

Hello, I'm the elder brother of Chinese menong green tea.
Welcome to my personal WeChat official account: 8 Kangyuan road!


1. Explanation of professional terms

1.1 Dao

Dao layer is called data access layer and persistence layer, and its full name is Data access object. It is a kind of bottom-level and basic operation. It is specific to the addition, deletion, modification and query of a table, that is, a Dao must correspond to a table in the database one by one. It encapsulates the basic operations of addition, deletion, modification and query, and queries data completely according to the requirements of the Domain, It is recommended that Dao only perform atomic operations, add, delete, modify and check.

1.2 Domain

The Domain layer considers business logic, such as filtering conditions, release or return, and data processing, to prepare for calling the Dao layer. A Domain can call one or a group of related Dao layers.

1.3 Service

The Service layer is called the Service layer, which is called the Service layer. The Service layer calls one or a group of Domain layers, which mainly shows the interfaces that need to be opened. Not all interfaces of the Domain layer need to be reflected in the Service layer, and only a few interfaces may be opened in the Service layer. In addition, the main interface needs to expand the accepted parameters as much as possible, that is, it can accommodate the access (Object) of various types of parameters, and then it needs to be converted in the Service layer for use by the Domain layer.

1.4 Controler

The controller is responsible for forwarding the request, accepting the parameters from the page, transmitting them to the Service for processing, receiving the return value, and then transmitting them to the page.

1.5 business logic

The user sends a request - > the controller handles the transmitted parameters - > the domain receives the control data and turns (you can return or enter the service - > service to verify the correctness of the data or whether it meets the business requirements - > Dao deposit

2 Introduction to mybatis generator

MyBatis Generator (MBG) is the code generator for MyBatis, MyBatis and iBATIS. It will generate code for all versions of MyBatis and iBATIS versions after version 2.2.0. It will introspect database tables (or many tables) and generate artifacts that can be used to access tables. This reduces the initial hassle of setting up objects and configuration files to interact with database tables. MBG seeks simple CRUD Most database operations (create, retrieve, update, delete) have a significant impact. You still need to manually write SQL and object code for connection queries or stored procedures.

2.1 MyBatis Generator will generate

2.1. 1 Java POJO s matching the table structure

This may include:

  • A class that matches the primary key of the table (if there is a primary key)
  • A class that matches the non primary key field of the table (except BLOB field)
  • Class containing the BLOB field of the table (if the table has a BLOB field)
  • Classes used to enable dynamic selection, updating, and deletion

There are appropriate inheritance relationships between these classes. Note that the generator can be configured to generate different types of POJO hierarchies - for example, if you prefer, you can choose to generate a single domain object for each table.

2.1.2 MyBatis / iBATIS compatible SQL Map XML file

MBG generates SQL for simple CRUD functions on each table in the configuration. The generated SQL statements include:

  • insert
  • Update by primary key
  • Update by example (using dynamic where clause)
  • Delete by primary key
  • Delete by example (using dynamic where clause)
  • Select by primary key
  • Select by example (using dynamic where clause)
  • make oneself an example

According to the structure of the table, these statements have different variants (for example, if the table has no primary key, MBG will not generate updates through the primary key function).

2.1.3 properly use the Java client class of the above object

The generation of java client classes is optional. MBG will generate the following types of Java clients for MyBatis 3.x:

  • Mapper interface for MyBatis 3.x mapper infrastructure

MBG will generate the following types of Java clients for iBATIS 2.x:

  • Spring framework compliant DAO
  • Only Daos that use iBATIS SQL mapping API. These Daos can generate two types: providing SqlMapClient through constructor or setter injection.
  • DAO conforming to iBATIS DAO framework (an optional part of iBATIS. This framework is not recommended now. We recommend that you use Spring framework)

The MyBatis generator is designed to run well in an iterative development environment and can be included in a continuous build environment as an Ant task or Maven plug-in. Important considerations when iteratively running MBG include:

  • If there is an existing file with the same name as the newly generated XML file, MBG will automatically merge the XML file. MBG will not overwrite any custom changes you have made to the XML file it generates. You can run it repeatedly without fear of losing custom changes to the XML. MBG will replace any XML elements generated in the previous run.
  • MBG does not merge Java files. It can overwrite existing files or save newly generated files with different unique names. If you make changes to the generated Java files and run MBG iteratively, you must merge the changes manually. MBG can automatically merge Java files when running as an Eclipse plug-in.

3 MyBatis Generator download

3.1 source code address

3.2 official documents

4 Mybatis Generator configuration and use

4.1 creation of database and data table

4.1.1 new database: mybatis demo

4.1.2 new data table ad

-- Table structure for table `ad`

/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
    `id`          int(11) NOT NULL AUTO_INCREMENT,
    `name`        varchar(63)  NOT NULL DEFAULT '' COMMENT 'Ad title',
    `link`        varchar(255) NOT NULL DEFAULT '' COMMENT 'Link address of the advertised product page or activity page',
    `url`         varchar(255) NOT NULL COMMENT 'Advertising pictures',
    `position`    tinyint(3) DEFAULT '1' COMMENT 'Advertising position: 1 is the home page',
    `content`     varchar(255)          DEFAULT '' COMMENT 'Activity content',
    `start_time`  datetime              DEFAULT NULL COMMENT 'Advertising start time',
    `end_time`    datetime              DEFAULT NULL COMMENT 'Advertising end time',
    `enabled`     tinyint(1) DEFAULT '0' COMMENT 'Start',
    `add_time`    datetime              DEFAULT NULL COMMENT 'Creation time',
    `update_time` datetime              DEFAULT NULL COMMENT 'Update time',
    `deleted`     tinyint(1) DEFAULT '0' COMMENT 'Logical deletion',
    PRIMARY KEY (`id`),
    KEY           `enabled` (`enabled`)

4.1.3 inserting data into data sheets

-- Dumping data for table `ad`

/*!40000 ALTER TABLE `ad` DISABLE KEYS */;
VALUES (1, 'Who is your dish', '', '', 1,' who is your dish ', NULL,
        NULL, 1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0),
       (2, 'Activity Food Festival', '', '', 1,' active food festival ', NULL, NULL,
        1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0),
       (3, 'Activity mother's Day', '', 'http://Yanxuan. Nosdn. 127. Net / 8e50c65fda145e6dd1bf4fb7ee0fcc. JPG ', 1,' active mother's day 5', NULL, NULL,
        1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0);
/*!40000 ALTER TABLE `ad` ENABLE KEYS */;

4.2 new project mybatis demo

4.2.1 import plug-in in pom.xml



4.2.2 preparation of configuration files

Create a new folder mybatis generator under the root directory of the project, create a generatorConfig.xml file, and write in the file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-// MyBatis Generator Configuration 1.0//EN"


    <context id="mysqlgenerator" targetRuntime="MyBatis3">
        <property name="autoDelimitKeywords" value="true"/>
        <!--have access to``Include field names to avoid field names and sql Reserved word conflict error-->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- Automatic generation toString method -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!-- Automatic generation equals Methods and hashcode method -->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>

        <!-- Unofficial plug-ins -->
        <!-- Query single data plug-in -->
        <plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>
        <!-- Query result selective return plug-in -->
        <plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/>
        <!-- Example Criteria Enhanced plug-in -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"/>
        <!-- data Model Attribute correspondence Column Get plug-ins -->
        <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
        <!-- Logical delete plug-in -->
        <plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
            <!-- The global logical deletion column and logical deletion value are configured here. Of course, in table The value configured in overrides the global configuration -->
            <!-- The type of a tombstone column can only be numeric, string, or Boolean -->
            <property name="logicalDeleteColumn" value="deleted"/>
            <!-- Logical deletion-Deleted value -->
            <property name="logicalDeleteValue" value="1"/>
            <!-- Logical deletion-Value not deleted -->
            <property name="logicalUnDeleteValue" value="0"/>

            <property name="suppressDate" value="true"/>
            <!--<property name="suppressAllComments" value="true"/>-->

        <!--Database connection information-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"

            <property name="useJSR310Types" value="true"/>

        <javaModelGenerator targetPackage="com.hyd.mybatisdemo.domain" targetProject="src/main/java"/>
        <sqlMapGenerator targetPackage="com.hyd.mybatisdemo.dao" targetProject="src/main/resources"/>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hyd.mybatisdemo.dao" targetProject="src/main/java"/>
        <!--Table name-->
        <table tableName="ad">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>


4.2.3 running plug-ins

Open Maven on the right side of the window, expand mybatis Demo - > plugin - > mybatis generator, and double-click mybatis generator: generate to see the console related information and the generated Dao, domain, com.hyd.mybatisdemo.dao

4.3 start use

4.3.1 create

public class AdService {
    private AdMapper adMapper;

    public List<Ad> queryIndex() {
        AdExample example = new AdExample();
        example.or().andPositionEqualTo((byte) 1).andDeletedEqualTo(false).andEnabledEqualTo(true);
        return adMapper.selectByExample(example);

    public List<Ad> querySelective(String name, String content, Integer page, Integer limit, String sort, String order) {
        AdExample example = new AdExample();
        AdExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        if (!StringUtils.isEmpty(content)) {
            criteria.andContentLike("%" + content + "%");

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);

        PageHelper.startPage(page, limit);
        return adMapper.selectByExample(example);

    public int updateById(Ad ad) {
        return adMapper.updateByPrimaryKeySelective(ad);

    public void deleteById(Integer id) {

    public void add(Ad ad) {

    public Ad findById(Integer id) {
        return adMapper.selectByPrimaryKey(id);

4.3.2 create

public class AdController {

    private AdService adService;

    public Object getad() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Map<String, Object> data = new HashMap<>();
        Callable<List> bannerListCallable = () -> adService.queryIndex();
        FutureTask<List> bannerTask = new FutureTask<>(bannerListCallable);
        try {
            data.put("banner", bannerTask.get());
        } catch (Exception e) {
        return ResponseUtil.ok(data);


4.3.3 test interface


5 project address

Gitee - Mybatis-demo

It's not easy to organize. Welcome Star and Fork, Thank you~~

Posted by rd2010 on Sun, 10 Oct 2021 07:16:42 -0700