We mentioned

MyBatis Generator (MBG) is a code Generator for MyBatis and iBATIS. It can automatically generate ORM layer code for all versions of MyBatis and iBATIS versions after 2.2.0, typically including poJOs, Mapper XML and Mapper interface that we need to write by hand. MyBatis Generator automatically generates ORM layer code that can handle most CRUD data table scenarios and is a productivity tool.

Welcome to My Personal Blog CodeSheep


Database preparation and engineering setup

  • First we prepare a MySQL tableuser_infoFor the following experiments

Insert several pieces of data:

  • Create a New Spring Boot project

  • Introduce the MyBatis Generator dependency

<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> < version > 1.3.7 < / version > < scope > provided < / scope > < / dependency >Copy the code
  • Introducing the MyBatis Generator Maven plugin
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> < version > 1.3.7 < / version > < configuration > < configurationFile > SRC/main/resources/mybatis - generator. XML < / configurationFile >  <overwrite>true</overwrite> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> </dependencies> </dependencies> </dependencies> </plugin>Copy the code

After the MyBatis Generator Maven plugin is introduced, you can see the new plugin options in the Maven plugin toolbar of the Spring Boot project, similar to the following:


Prepare the MyBatis Generator configuration file

MyBatis Generator also requires a configuration file in XML format. This file is located in the XML configuration introduced in the MyBatis Generator Maven plugin above. The SRC/main/resources/mybatis – generator. XML configuration used by this paper is given below:

<?xml version="1.0" encoding="UTF-8"? >

      

<generatorConfiguration>

    <context id="MySql" defaultModelType="flat">     

        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />

        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="JDBC: mysql: / / 121.196.123.245:3306 / demo"
                userId="root"
                password="xxxxxx" />

        <javaModelGenerator targetPackage="cn.codesheep.springbt_mybatis_generator.entity" targetProject="src/main/java"></javaModelGenerator>

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

        <javaClientGenerator targetPackage="cn.codesheep.springbt_mybatis_generator.mapper" targetProject="src/main/java" type="XMLMAPPER"></javaClientGenerator>

        <table tableName="user_info">
            <property name="modelOnly" value="false"/>
        </table>

    </context>

</generatorConfiguration>
Copy the code

A few key configurations in the XML above are summarized as follows:

  • < jdbcConnection />Database connection configuration is critical
  • <javaModelGenerator />Specifies which package to place the automatically generated POJOs under
  • <sqlMapGenerator />Specifies which package to place the automatically generated mapper.xml
  • <javaClientGenerator />Specifies which package to place the automatically generated DAO interface under
  • <table />Specifies the name of the data table. You can use the _ and % wildcards

For more information on the configuration of MyBatis Generator, please refer to the official documentation.


Run the MyBatis Generator

Run MyBatis Generator directly through the Maven graphical plug-in of IDEA. The automatic generation process and generated results are shown in the following figure:

MyBatis Generator generates poJOs, MAPper XML, and Mapper interface automatically with MyBatis Generator.


How is the automatically generated code used

We found that the code automatically generated by MyBatis Generator contains an Example file, such as the UserInfoExample file mentioned above. In fact, the Example file is of great benefit to rapid development and can save a lot of time to write SQL statements. Here are some practical examples:

  • Single – term fuzzy search + sort

In our example, if I want to do a fuzzy search on MySQL user_info using user_name and sort the results, UserInfoExample can be used quickly and easily:

@Autowired
private UserInfoMapper userInfoMapper;

public List<UserInfo> searchUserByUserName( String userName ) {

    UserInfoExample userInfoExample = new UserInfoExample();
    userInfoExample.createCriteria().andUserNameLike( The '%'+ userName +The '%' ); // Set fuzzy search criteria

    String orderByClause = "user_name DESC";
    userInfoExample.setOrderByClause( orderByClause );  // Sets the condition for sorting by a field

    return userInfoMapper.selectByExample( userInfoExample );
}
Copy the code
  • Multi – condition accurate search

For example, if we want to search user_info by phone number and user_name, we can do the following:

public List<UserInfo> multiConditionsSearch( UserInfo userInfo ) {

    UserInfoExample userInfoExample = new UserInfoExample();
    UserInfoExample.Criteria criteria = userInfoExample.createCriteria();

    if(!"".equals(userInfo.getPhone()) )
        criteria.andPhoneEqualTo( userInfo.getPhone() );
    if(!"".equals(userInfo.getUserName()) )
        criteria.andUserNameEqualTo( userInfo.getUserName() );

    return userInfoMapper.selectByExample( userInfoExample );
}
Copy the code

It is obvious that we are writing code logic directly instead of writing SQL statements, so it is straightforward and easy to understand!


Remember after

Due to the limited ability, if there is a mistake or improper place, please also criticize and correct, study together!

  • My Personal Blog: CodeSheep program sheep


To subscribe to CodeSheep’s public account, long press or scan below, you can get more practical, understandable and reproducible original articles