编程知识 cdmana.com

Free your hands! MyBatis official code generation tool to awesome!

When we use MyBatis In the process of , If all entity classes and single tables CRUD Code needs to be written by hand , It's going to be quite a hassle .MyBatis Generator official code MyBatis Generator Can help us solve this problem , In my open source project mall This code generator is also used in , It's good to get used to it . This article will introduce MyBatis Generator How to use it and how to use it , I hope that's helpful !

SpringBoot Actual e-commerce projects mall(40k+star) Address :https://github.com/macrozheng/mall

brief introduction

MyBatis Generator( abbreviation MBG) yes MyBatis Official code generation tool . Entity classes can be generated directly from database tables 、 Single table CRUD Code 、mapper.xml file , To free our hands !

Start using

First of all, we will use an introductory example to MBG To use , The example will contain the basic CRUD operation .

Integrate MBG

  • stay pom.xml Add the following dependency , Mainly added MyBatis、PageHelper、Druid、MBG and MySQL Drive, etc ;
<dependencies>
    <!--SpringBoot Integrate MyBatis-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.3</version>
    </dependency>
    <!--MyBatis Paging plug-ins -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.3.0</version>
    </dependency>
    <!-- Integrate druid Connection pool -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!-- MyBatis  generator  -->
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-core</artifactId>
        <version>1.4.0</version>
    </dependency>
    <!--Mysql Database driven -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>
</dependencies>
  • stay application.yml Data sources and MyBatis Of mapper.xml File path configuration , Make an appointment here ,MBG The generated ones are placed in resources/com/**/mapper Under the table of contents , Custom placed in resources/dao Under the table of contents ;
#  Data source configuration 
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

# MyBatis mapper.xml Path configuration 
mybatis:
  mapper-locations:
    - classpath:dao/*.xml
    - classpath*:com/**/mapper/*.xml
  • add to Java To configure , For scanning code Mapper Interface path , There's a deal here ,MBG The generated ones are placed in mapper It's a bag , Custom placed in dao It's a bag .
/**
 * MyBatis Configuration class 
 * Created by macro on 2019/4/8.
 */
@Configuration
@MapperScan({"com.macro.mall.tiny.mbg.mapper","com.macro.mall.tiny.dao"})
public class MyBatisConfig {
}

Using a code generator

  • In the use of MBG Before generating code , We also need to configure it , First, in the generator.properties Configure the database connection information in the file ;
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.userId=root
jdbc.password=root
  • And then in generatorConfig.xml In the document MBG To configure , You can refer to the comments directly for the description of configuration properties ;
<?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"/>
    <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>
        <!-- Generate mapper.xml The original file will be overwritten -->
        <plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin" />
        <!--  Generate serialization methods for models -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
        <!--  For the generated Java The model creates a toString Method  -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!-- Can be custom generated model Code comments for -->
        <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">
            <!--  Remove automatically generated comments or not  true: yes  : false: no  -->
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
        <!-- Configure database connections -->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">
            <!-- solve mysql Drive upgrade to 8.0 The problem of not generating the specified database code after -->
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>
        <!-- Specify generation model The path of -->
        <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-generator\src\main\java"/>
        <!-- Specify generation mapper.xml The path of -->
        <sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper" targetProject="mall-tiny-generator\src\main\resources"/>
        <!-- Specify generation mapper The path of the interface -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"
                             targetProject="mall-tiny-generator\src\main\java"/>
        <!-- Generate all tables tableName Set to %-->
        <table tableName="ums_admin">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="ums_role">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="ums_admin_role_relation">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="ums_resource">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="ums_resource_category">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
  • It's worth mentioning here targetRuntime This attribute , The code generated by setting different properties and the usage of generated code will be different , Commonly used MyBatis3 and MyBatis3DynamicSql Two kinds of , What we use here is MyBatis3;
  • If you want to customize MBG If the generated code , You can write one by yourself CommentGenerator To inherit DefaultCommentGenerator, Here I customize the generation of entity class code , Added Swagger Support for annotations ;
package com.macro.mall.tiny.mbg;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/**
 *  Custom annotation generator 
 * Created by macro on 2018/4/26.
 */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX="Example";
    private static final String MAPPER_SUFFIX="Mapper";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";

    /**
     *  Set user configured parameters 
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     *  Add a comment to the field 
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        // Judge whether to add remark information according to parameters and remarks 
        if(addRemarkComments&&StringUtility.stringHasValue(remarks)){
            // Special characters in the database need to be escaped 
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            // to model Field addition of swagger annotation 
            field.addJavaDocLine("@ApiModelProperty(value = \""+remarks+"\")");
        }
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        // Only in model Add swagger Import annotation class 
        String fullyQualifiedName = compilationUnit.getType().getFullyQualifiedName();
        if(!fullyQualifiedName.contains(MAPPER_SUFFIX)&&!fullyQualifiedName.contains(EXAMPLE_SUFFIX)){
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
        }
    }
}
  • Finally, let's write a Generator Class is used to generate code , Direct operation main Method to generate all the code ;
/**
 *  Used in the production of MBG Code for 
 * Created by macro on 2018/4/26.
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG  Warning messages during execution 
        List<String> warnings = new ArrayList<String>();
        // When the generated code repeats , Covering the original code 
        boolean overwrite = true;
        // Read our  MBG  The configuration file 
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        // establish  MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        // Execute generate code 
        myBatisGenerator.generate(null);
        // Output warning messages 
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}
  • Everything is all set. , perform main Method , The generated code structure information is as follows .

Implement the basic CRUD operation

What we use here is mall-tiny Related table of authority management function in project , For details, please refer to 《 Still building projects from scratch ? Hand rolled a rapid development scaffold !》.
  • Look at the MBG Generated Mapper Interface , The discovery already contains the basic CRUD Method , Specifically SQL The realization is already in mapper.xml Generated in the , Single table CRUD Call the corresponding method directly ;
public interface UmsAdminMapper {
    long countByExample(UmsAdminExample example);

    int deleteByExample(UmsAdminExample example);

    int deleteByPrimaryKey(Long id);

    int insert(UmsAdmin record);

    int insertSelective(UmsAdmin record);

    List<UmsAdmin> selectByExample(UmsAdminExample example);

    UmsAdmin selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") UmsAdmin record, @Param("example") UmsAdminExample example);

    int updateByExample(@Param("record") UmsAdmin record, @Param("example") UmsAdminExample example);

    int updateByPrimaryKeySelective(UmsAdmin record);

    int updateByPrimaryKey(UmsAdmin record);
}
  • There are some in the generated code Example class , such as UmsAdminExample, We can think of it as a condition builder , Used to build SQL Various conditions in a statement ;

  • Make good use of MBG The generated code can complete the construction of a single table CRUD Operation , For example, the following most common operations .
/**
 *  Background user management Service Implementation class 
 * Created by macro on 2020/12/8.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminDao adminDao;

    @Override
    public void create(UmsAdmin entity) {
        adminMapper.insert(entity);
    }

    @Override
    public void update(UmsAdmin entity) {
        adminMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public UmsAdmin select(Long id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<UmsAdmin> listAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return adminMapper.selectByExample(new UmsAdminExample());
    }
}

Advanced use

Want to use it well MBG, The basic operation above is not enough , It also needs some advanced skills .

Conditions of the query

Use Example Class to build query conditions can be very convenient to achieve conditional query .
  • Here, we take the example of querying background users by user name and status and arranging them in descending order by creation time ,SQL The implementation is as follows ;
SELECT
    id,
    username,
    PASSWORD,
    icon,
    email,
    nick_name,
    note,
    create_time,
    login_time,
STATUS 
FROM
    ums_admin 
WHERE
    ( username = 'macro' AND STATUS IN ( 0, 1 ) ) 
ORDER BY
    create_time DESC;
  • Corresponding Java The code implementation is as follows .
/**
 *  Background user management Service Implementation class 
 * Created by macro on 2020/12/8.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    
    @Override
    public List<UmsAdmin> list(Integer pageNum, Integer pageSize, String username, List<Integer> statusList) {
        PageHelper.startPage(pageNum, pageSize);
        UmsAdminExample umsAdminExample = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = umsAdminExample.createCriteria();
        if(StrUtil.isNotEmpty(username)){
            criteria.andUsernameEqualTo(username);
        }
        criteria.andStatusIn(statusList);
        umsAdminExample.setOrderByClause("create_time desc");
        return adminMapper.selectByExample(umsAdminExample);
    }
}

Subquery

Use MBG The generated code does not implement subqueries , I need to write by myself SQL Realization .
  • Here by role ID For example, query background users , So let's define a UmsAdminDao Interface , It is agreed that Dao The methods stored in it are user-defined SQL Method of implementation , First, in the Dao Add to interface subList Method ;
/**
 * Created by macro on 2020/12/9.
 */
public interface UmsAdminDao {

    List<UmsAdmin> subList(@Param("roleId") Long roleId);
}
  • And then create a UmsAdminDao.xml file , Corresponding UmsAdminDao Interface SQL Realization , Write the corresponding SQL Realization , Pay attention to the resultMap MBG It's already generated for us , No need to write by yourself .
<select id="subList" resultMap="com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap">
    SELECT *
    FROM ums_admin
    WHERE id IN (SELECT admin_id FROM ums_admin_role_relation WHERE role_id = #{roleId})
</select>

Group and Join Inquire about

Group and Join Queries can't be used either MBG The generated code implements .
  • Here is an example of counting the number of background users by role , First, in the Dao Add to interface groupList Method ;
public interface UmsAdminDao {

    List<RoleStatDto> groupList();
}
  • And then in mapper.xml Add the corresponding SQL Realization , We can list the aliases for the queries , Map columns directly to resultType In the defined object .
<select id="groupList" resultType="com.macro.mall.tiny.domain.RoleStatDto">
    SELECT ur.id        AS roleId,
           ur.NAME      AS roleName,
           count(ua.id) AS count
    FROM ums_role ur
             LEFT JOIN ums_admin_role_relation uarr ON ur.id = uarr.role_id
             LEFT JOIN ums_admin ua ON uarr.admin_id = ua.id
    GROUP BY ur.id;
</select>

Conditions delete

Conditional deletion is simple , Use it directly Example Class to construct deletion conditions .
  • Here, take deleting background users by user name as an example ,SQL The implementation is as follows ;
DELETE 
FROM
    ums_admin 
WHERE
    username = 'andy';
  • Corresponding Java The implementation of is .
/**
 *  Background user management Service Implementation class 
 * Created by macro on 2020/12/8.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    @Override
    public void deleteByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        adminMapper.deleteByExample(example);
    }
}

Condition modification

Conditional deletion is simple , Use it directly Example Class construct modify condition , Then pass in and modify the parameters .
  • Here you have to press the designation ID For example, modify the status of background users ,SQL The implementation is as follows ;
UPDATE ums_admin 
SET STATUS = 1 
WHERE
    id IN ( 1, 2 );
  • Corresponding Java The implementation of is .
/**
 *  Background user management Service Implementation class 
 * Created by macro on 2020/12/8.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    @Override
    public void updateByIds(List<Long> ids, Integer status) {
        UmsAdmin record = new UmsAdmin();
        record.setStatus(status);
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andIdIn(ids);
        adminMapper.updateByExampleSelective(record,example);
    }
}

One-to-many query

One to many queries cannot be used directly MBG The generated code implements , Handwriting required SQL Realization , And use resultMap To map the result set .
  • Here you can press ID Query background user information ( Contains a list of corresponding roles ) For example , First in Dao Add to interface selectWithRoleList Method ;
/**
 * Created by macro on 2020/12/9.
 */
public interface UmsAdminDao {

    AdminRoleDto selectWithRoleList(@Param("id") Long id);
}
  • And then in mapper.xml Add the corresponding SQL Realization , Here's a tip , You can alias the columns found in the role table , Add one role_ Prefix ;
<select id="selectWithRoleList" resultMap="AdminRoleResult">
    SELECT ua.*,
           ur.id          AS role_id,
           ur.NAME        AS role_name,
           ur.description AS role_description,
           ur.create_time AS role_create_time,
           ur.STATUS      AS role_status,
           ur.sort        AS role_sort
    FROM ums_admin ua
             LEFT JOIN ums_admin_role_relation uarr ON ua.id = uarr.admin_id
             LEFT JOIN ums_role ur ON uarr.role_id = ur.id
    WHERE ua.id = #{id}
</select>
  • And then define a name called AdminRoleResult Of ResultMap, adopt collection The label will be marked directly with role_ The first column maps to UmsRole Just go to the object .
<resultMap id="AdminRoleResult" type="com.macro.mall.tiny.domain.AdminRoleDto"
           extends="com.macro.mall.tiny.mbg.mapper.UmsAdminMapper.BaseResultMap">
    <collection property="roleList" resultMap="com.macro.mall.tiny.mbg.mapper.UmsRoleMapper.BaseResultMap"
                columnPrefix="role_">
    </collection>
</resultMap>

One-to-one query

One to one queries cannot be used directly MBG The generated code implements , Handwriting required SQL Realization , And use resultMap To map the result set .
  • Here you can press ID Query resource information ( Including classification information ) For example , First in Dao Add to interface selectResourceWithCate Method ;
/**
 * Created by macro on 2020/12/9.
 */
public interface UmsAdminDao {

    ResourceWithCateDto selectResourceWithCate(@Param("id")Long id);
}
  • And then in mapper.xml Add the corresponding SQL Realization , You can give an alias to a column that is found in the taxonomy table , Add one cate_ Prefix ;
<select id="selectResourceWithCate" resultMap="ResourceWithCateResult">
    SELECT ur.*,
           urc.id          AS cate_id,
           urc.`name`      AS cate_name,
           urc.create_time AS cate_create_time,
           urc.sort        AS cate_sort
    FROM ums_resource ur
             LEFT JOIN ums_resource_category urc ON ur.category_id = urc.id
    WHERE ur.id = #{id}
</select>
  • And then define a name called ResourceWithCateResult Of ResultMap, adopt association The label will be marked directly with cate_ The first column maps to UmsResourceCategory Just go to the object .
<resultMap id="ResourceWithCateResult" type="com.macro.mall.tiny.domain.ResourceWithCateDto"
           extends="com.macro.mall.tiny.mbg.mapper.UmsResourceMapper.BaseResultMap">
    <association property="resourceCategory"
                 resultMap="com.macro.mall.tiny.mbg.mapper.UmsResourceCategoryMapper.BaseResultMap"
                 columnPrefix="cate_">
    </association>
</resultMap>

summary

in general MyBatis Generator official code MBG It's still very powerful , Some common single tables can be generated CRUD Method , Reduced our workload . But for subqueries 、 Multi table query and some complex query support is a little weak , Still need to be in mapper.xml Chinese handwriting SQL Realization .

Reference material

Official documents :https://mybatis.org/generator...

Project source address

https://github.com/macrozheng...

this paper GitHub https://github.com/macrozheng/mall-learning Included , Welcome to Star!

版权声明
本文为[macrozheng]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224100315743r.html

Scroll to Top