Mybatis generator maven example 2016-11-24 21:01

I have wrote a tutorial how to generator Mybatis entity and mapper by using idea Mybatis plugin. In this blog I will how you how to generator Mybatis entity and mapper by using maven plugin. Before using IDEA plugin you need pay for it, maven plugin is free instead.

The structure of project

│  ├─java
│  │  └─com
│  │      └─henryxi
│  │          └─mybatis
│  │              └─generator
│  │                  ├─entity
│  │                  └─mapper
│  └─resources
│          mybatis-generator.xml

You need create the entity and mapper package before generating.

The content of pom


The content of mybatis-generator

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

    <!-- !!!! Driver Class Path !!!! -->
    <classPathEntry location="C:\Users\Administrator\.IntelliJIdea2016.1\config\jdbc-drivers\mysql-connector-java-5.1.35-bin.jar"/>

    <context id="context" targetRuntime="MyBatis3">
            <property name="suppressAllComments" value="false"/>
            <property name="suppressDate" value="true"/>

        <!-- !!!! Database Configurations !!!! -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/db" userId="root" password="123456"/>

            <property name="forceBigDecimals" value="false"/>

        <!-- !!!! Model Configurations !!!! -->
        <javaModelGenerator targetPackage="com.henryxi.mybatis.generator.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>

        <!-- !!!! Mapper XML Configurations !!!! -->
        <sqlMapGenerator targetPackage="com.henryxi.mybatis.generator.mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>

        <!-- !!!! Mapper Interface Configurations !!!! -->
        <javaClientGenerator targetPackage="com.henryxi.mybatis.generator.mapper" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>

        <!-- !!!! Table Configurations !!!! -->
        <table tableName="users" domainObjectName="User">
            <property name="ignoreQualifiersAtRuntime" value="true"/>
            <property name="modelOnly" value="false"/>

Run mvn mybatis-generator:generate command it will generate entities and mapper for you. The sql of creating users table like following.

CREATE TABLE `users` (
  `user_name` varchar(500) NOT NULL,
  `pwd` varchar(500) NOT NULL,
  `email` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_user_name_uindex` (`user_name`)

After generating the structure like following

│  ├─java
│  │  └─com
│  │      └─henryxi
│  │          └─mybatis
│  │              └─generator
│  │                  ├─entity
│  │                  │
│  │                  │
│  │                  │
│  │                  └─mapper
│  │                
│  │
│  └─resources
│      │  mybatis-generator.xml
│      │
│      └─com
│          └─henryxi
│              └─mybatis
│                  └─generator
│                      └─mapper
│                              UserMapper.xml

How to use generated entity and mapper

Add mybatis-config.xml in resources directory. The content of it like following.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"

        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>

    <!-- Continue going here -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
        <mapper resource="com/henryxi/mybatis/generator/mapper/UserMapper.xml"/>

Use generated entity and mapper like following.

public static void main(String[] args) throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        UserExample example = new UserExample();
        List<User> allRecords = mapper.selectByExample(example);
        for (User user : allRecords) {
            System.out.println("user id: " + user.getId());
            System.out.println("user name: " + user.getUserName());
    } finally {