MyBatis3 (4) 框架整合

740 阅读3分钟

1. 整合准备

流程:

  • 添加依赖:
    • mybatis:mybatis/mysql-connector-java/commons-dbcp2
    • spring:spring-core/beans/aspects/tx/jdbc
    • spring:spring-context/context-support/expression
    • log:log4j-core/log4j/slf4j-api/slf4j-log4j12
    • mybatis-spring:mybatis-spring
    • other:lombok/junit/spring-test
  • 开发对应小狗表的小狗实体类。
  • 开发mybatis主配文件:配置别名,SQL配置文件扫描和数据源交给spring做。

源码: /mybatis3/

  • res: pom.xml
 <properties>
        <spring>4.3.14.RELEASE</spring>
    </properties>

    <dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--log4j-core-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>

        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!--slf4j-api-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!--slf4j-log4j12-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>

        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
            <scope>runtime</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <optional>true</optional>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--spring-core-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-beans-->
        <dependency>
            <groupId>org.springframework
            </groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-context-->
        <dependency>
            <groupId>org.springframework
            </groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-context-support-->
        <dependency>
            <groupId>org.springframework
            </groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-expression-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-tx-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--spring-aspects-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring}</version>
        </dependency>

        <!--commons-dbcp2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!--mybatis-spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>

        <!--ant-->
        <!--
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.9.6</version>
        </dependency>
        -->

        <!--asm-->
        <!--
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>5.2</version>
        </dependency>
        -->

        <!--cglib-->
        <!--
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
        -->

        <!--commons-logging-->
        <!--
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        -->

        <!--ognl-->
        <!--
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.16</version>
        </dependency>
        -->
    </dependencies>

-res:sql


CREATE TABLE IF NOT EXISTS `dog`
(
    `id`     INT(11) AUTO_INCREMENT PRIMARY KEY,
    `name`   VARCHAR(50)  NOT NULL COMMENT '小狗姓名',
    `gender` TINYINT(1)   NULL COMMENT '小狗性别',
    `age`    INT(3)       NULL COMMENT '小狗年龄',
    `info`   VARCHAR(500) NULL COMMENT '小狗信息'
)
    COMMENT '小狗表';
  • res: classpath:mybatis-sm.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>

    <typeAliases>
        <package name="com.yap.pojo"/>
    </typeAliases>

</configuration>
  • src: c.y.pojo.Dog
package com.yap.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @Author Yap
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dog implements Serializable {
    private Integer id;
    private String name;
    private Integer gender;
    private Integer age;
    private String info;
}

2. 原生DAO整合

流程:

  • 开发SQL配置文件:编写CRUD语句块,不使用接口所以无需四大对应。
  • 开发数据层接口和实现类:继承SM整合包中的 SqlSessionDaoSupport
    • getSqlSession():获取一个spring管理的session对象,不支持手动提交回滚和关闭。
  • 开发spring主配文件并加载属性文件:
    • <context:property-placeholder location="classpath:属性文件">
  • 在spring主配文件中IOC连接池 o.a.c.d.BasicDataSource
    • 将驱动串等数据源信息DI给DBCP连接池的对应属性。
  • 在spring主配文件中IOC会话工厂 o.m.s.SqlSessionFactoryBean
    • 将mybatis的主配文件DI给 configLocation 属性。
    • 将连接池DI给 dataSource 属性。
    • 将SQL配置文件DI给 mapperLocations 属性。
  • 在spring主配中IOC数据层实现类:
    • 将会话工厂DI给 sqlSessionFactory 属性(其父类的SET方法)。

源码: /mybatis3/

  • res: classpath:sprint/spring-sm.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:property-placeholder location="classpath:jdbc/db.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="mybatis-sm.xml"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations">
            <array>
                <value>com/yap/mapper/DogMapper.xml</value>
            </array>
        </property>
    </bean>

    <bean class="com.yap.dao.impl.DogDaoImpl">
        <property name="sqlSessionFactory" ref="factory"/>
    </bean>
</beans>
  • res: c.j.mapper.DogMapper.xml
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="dogSpace">

        <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO `dog`
        VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})
    </insert>

    <select id="findById" resultType="dog">
        SELECT `id`, `name`, `gender`, `age`, `info`
        FROM mybatis.`dog`
        WHERE `id` = #{id}
    </select>

    <update id="updateById">
        UPDATE mybatis.`dog`
        <set>
            <if test='name != null'>`name` = #{name},</if>
            <if test='age != null'>`age` = #{age},</if>
            <if test='gender != null'>`gender` = #{gender},</if>
        </set>
        <where>
            id = #{id}
        </where>
    </update>

    <delete id="deleteById">
        DELETE
        FROM mybatis.`dog`
        WHERE `id` = #{id}
    </delete>

</mapper>
  • src: c.y.dao.DogDao
package com.yap.dao;
import com.yap.pojo.Dog;

/**
 * @author yap
 */
public interface DogDao {

    /**
     * 添加一只小狗
     *
     * @param dog 小狗实体
     */
    void insert(Dog dog);

    /**
     * 通过主键查询一只小狗
     *
     * @param id 主键
     * @return 一只小狗
     */
    Dog findById(int id);

    /**
     * 通过主键查询修改一只小狗
     *
     * @param dog 小狗实体
     */
    void updateById(Dog dog);

    /**
     * 通过主键查询删除一只小狗
     *
     * @param id 主键
     */
    void deleteById(int id);
}
  • src: c.y.dao.impl.DogDaoImpl
package com.yap.dao.impl;


import com.yap.dao.DogDao;
import com.yap.pojo.Dog;
import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
 * @author yap
 */
public class DogDaoImpl extends SqlSessionDaoSupport implements DogDao {
    @Override
    public void insert(Dog dog) {
        getSqlSession().insert("dogSpace.insert", dog);
    }

    @Override
    public Dog findById(int id) {
        return getSqlSession().selectOne("dogSpace.findById", id);
    }

    @Override
    public void updateById(Dog dog) {
        getSqlSession().update("dogSpace.updateById", dog);
    }

    @Override
    public void deleteById(int id) {
        getSqlSession().delete("dogSpace.deleteById", id);
    }
  • tst: c.y.sm.DogTest
package com.yap.sm;


import com.yap.dao.DogDao;
import com.yap.pojo.Dog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author yap
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-sm.xml")
public class DogTest {

    @Autowired
    private DogDao dogDao;

    @Test
    public void insert() {
        dogDao.insert(new Dog(4, "旺财", 1, 5, "哈士奇"));
    }

    @Test
    public void findById() {
        System.out.println(dogDao.findById(3));
    }

    @Test
    public void updateById() {
        dogDao.updateById(new Dog(2, "aa", 1, 5, "aa"));
    }

    @Test
    public void deleteById() {
        dogDao.deleteById(2);
    }
}

3. 接口Mapper整合

流程:

  • 开发SQL配置文件:编写CRUD语句块,需要和接口四大对应。
  • 开发Mapper接口,建议与SQL配置文件同名同包。
  • 开发spring主配文件并加载属性文件:
    • <context:property-placeholder location="classpath:属性文件">
  • 在spring主配文件中IOC连接池 o.a.c.d.BasicDataSource
    • 将驱动串等数据源信息DI给DBCP连接池的对应属性。
  • 在spring主配文件中IOC会话工厂 o.m.s.SqlSessionFactoryBean
    • 将mybatis的主配文件DI给 configLocation 属性。
    • 将连接池DI给 dataSource 属性。
    • 将SQL配置文件DI给 mapperLocations 属性,接口和配置文件同名同包时可省略。
  • 在spring主配文件中IOC接口扫描类 o.m.s.m.MapperFactoryBean
    • 将接口类全名DI给 mapperInterface 属性。
    • 将会话工厂DI给 sqlSessionFactory 属性。
  • 在spring主配文件中IOC接口包扫描类 o.m.s.m.MapperScannerConfigurer
    • 将接口所在包名DI给 basePackage 属性。
    • 包中所有接口的 <bean> 的id都默认为接口名首字母小写。
  • 在spring主配文件中IOC单个接口 o.m.s.m.MapperFactoryBean
    • 将接口全名DI给 mapperInterface 属性。
    • 将会话工厂DI给 sqlSessionFactory 属性。
    • 此方法与接口包扫描方法不共存。

源码: /mybatis3/ -res:sql

CREATE TABLE IF NOT EXISTS `cat`
(
    `id`     INT(11) AUTO_INCREMENT PRIMARY KEY,
    `name`   VARCHAR(50)  NOT NULL COMMENT '小猫姓名',
    `gender` TINYINT(1)   NULL COMMENT '小猫性别',
    `age`    INT(3)       NULL COMMENT '小猫年龄',
    `info`   VARCHAR(500) NULL COMMENT '小猫信息'
)
    COMMENT '小猫表';

  • res: classpath:mybatis-sm.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>

    <typeAliases>
        <package name="com.yap.pojo"/>
    </typeAliases>

</configuration>
  • src: c.y.pojo.Cat
package com.yap.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @Author Yap
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Cat implements Serializable {
    private Integer id;
    private String name;
    private Integer gender;
    private Integer age;
    private String info;
}

  • res: classpath:c.j.mapper.CatMapper.xml
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yap.mapper.CatMapper">

    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO mybatis.`cat`
        VALUES (#{id}, #{name}, #{gender}, #{age}, #{info})
    </insert>

    <select id="findById" resultType="cat">
        SELECT `id`, `name`, `gender`, `age`, `info`
        FROM mybatis.`cat`
        WHERE `id` = #{id}
    </select>

    <update id="updateById">
        UPDATE mybatis.`cat`
        <set>
            <if test='name != null'>`name` = #{name},</if>
            <if test='age != null'>`age` = #{age},</if>
            <if test='gender != null'>`gender` = #{gender},</if>
        </set>
        <where>
            id = #{id}
        </where>
    </update>

    <delete id="deleteById">
        DELETE
        FROM mybatis.`cat`
        WHERE `id` = #{id}
    </delete>

</mapper>
  • res: classpath:sprint/spring-cat.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:property-placeholder location="classpath:jdbc/db.properties"/>

    <bean id="catDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="catFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="mybatis-sm.xml"/>
        <property name="dataSource" ref="catDataSource"/>
        <property name="mapperLocations">
            <array>
                <value>com/yap/mapper/CatMapper.xml</value>
            </array>
        </property>
    </bean>

    <!--单独配置Mapper接口-->
    <bean id="catMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.yap.mapper.CatMapper"/>
        <property name="sqlSessionFactory" ref="catFactory"/>
    </bean>

    <!--整体包扫描
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yap.mapper"/>
    </bean>
    -->

</beans>
  • src: c.j.mapper.CatMapper
package com.yap.mapper;

import com.yap.pojo.Cat;

/**
 * @author yap
 */
public interface CatMapper {

    /**
     * 添加一只小猫
     *
     * @param cat 小猫实体
     */
    void insert(Cat cat);

    /**
     * 根据主键查询一只小猫
     *
     * @param id 主键
     * @return 一只小猫
     */
    Cat findById(int id);

    /**
     * 根据主键修改一只小猫
     *
     * @param cat 小猫实体
     */
    void updateById(Cat cat);

    /**
     * 根据主键删除一只小猫
     *
     * @param id 主键
     */
    void deleteById(int id);
}
  • tst: c.j.sm.CatTest
package com.yap.sm;

import com.yap.mapper.CatMapper;
import com.yap.pojo.Cat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author yap
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-cat.xml")
public class CatTest {

    @Autowired
    private CatMapper catMapper;

    @Test
    public void insert() {
        catMapper.insert(new Cat(1, "加肥", 1, 5, "加菲猫"));
    }

    @Test
    public void findById() {
        System.out.println(catMapper.findById(1));
    }

    @Test
    public void updateById() {
        catMapper.updateById(new Cat(1, "汤姆", 2, 15, "英短"));
    }

    @Test
    public void deleteById() {
        catMapper.deleteById(1);
    }
}

4. 逆向工程

概念: mybatis逆向工程用于根据数据表生成对应的实体类,包含CRUD语句块的SQL配置文件,对应SQL配置文件的Mapper接口,mybatis主配置文件等,仅支持单表:

  • 添加依赖:
    • mybatis/mybatis-generator-core/mysql-connector-java
  • 开发逆向工程主配文件:放在工程的根目录下,而非classpath下:
    • <plugin>:配置逆向工程插件,如序列化,toString() 等。
    • <commentGenerator>:配置是否添加工程注释。
    • <jdbcConnection>:配置JDBC连库信息。
    • <javaTypeResolver>:配置实体类个别属性类型解析规则。
    • <javaModelGenerator>:配置实体类生成位置。
    • <sqlMapGenerator>:配置SQL配置文件生成位置。
    • <javaClientGenerator>:配置Mapper接口生成位置。
    • <table>:配置根据哪些数据库表生成信息。
  • 开发主类并使用main方法运行逆向工程:再次生成时要先将之前生成的所有文件删除,否则信息叠加。

源码: /mybatis3-generator/

  • res: pom.xml
    <dependencies>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>

        <!--maven打包时将*Mapper文件一并打包-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*Mapper.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!--配置jdk的编译版本,默认JDK5-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • res: generator.xml
<?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>

    <!--targetRuntime 用于指定运行环境-->
    <context id="yap" targetRuntime="mybatis3">

        <!--为生成的实体类实现Serializable接口-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <!--为生成的实体类重写toString()-->
        <!--<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>-->

        <!--配置mybatis主配文件-->
        <plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">
            <property name="fileName" value="mybatis.xml"/>
            <property name="targetPackage" value="mybatis"/>
            <property name="targetProject" value="mybatis3-generator\src\main\resources"/>
        </plugin>

        <!--镇压代码注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--tinyInt1IsBit=false: 长度为1的tinyint和int不认为是bit,即不映射为boolean类型-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        userId="mybatis"
                        password="mybatis"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/mybatis?tinyInt1IsBit=false">
            <property name="useUnicode" value="true"/>
            <property name="characterEncoding" value="utf-8"/>
            <property name="serverTimezone" value="UTC"/>

            <!--true表示仅生成指定数据库中的指定表,false表示生成所有数据库中的同名表-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <javaTypeResolver>
            <!--true表示将decimal和numberic类型解析为java.math.BigDecimal-->
            <!--false表示将decimal和numberic类型解析为java.math.Integer,默认-->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--实体类配置-->
        <javaModelGenerator targetProject="mybatis3-generator\src\main\java" targetPackage="com.joezhou.generator.pojo">

            <!--不生成 "schema" 子包-->
            <property name="enableSubPackages" value="false"/>

            <!--清理从数据库返回的值的前后空格-->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--SQL配置文件配置-->
        <sqlMapGenerator targetProject="mybatis3-generator\src\main\resources" targetPackage="com.joezhou.generator.mapper">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!--Mapper接口配置-->
        <javaClientGenerator type="XMLMAPPER" targetProject="mybatis3-generator\src\main\java" targetPackage="com.joezhou.generator.mapper">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!--数据库表配置-->
        <!--即使数据库id字段有符号也映射为java.lang.Integer类型-->
        <table schema="mybatis" tableName="user">
            <columnOverride column="id" javaType="java.lang.Integer"/>
            <columnOverride column="gender" javaType="java.lang.Integer"/>
        </table>

    </context>

</generatorConfiguration>
  • src: c.y.app.Generator
package com.yap.app;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yap
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<>();
        new MyBatisGenerator(new ConfigurationParser(warnings).parseConfiguration(
                new File("mybatis3-generator/generator.xml")),
                new DefaultShellCallback(true), warnings)
                .generate(null);
        System.out.println("generate over...");
    }
}
  • sql:逆向工程生成的用户表来进行基础测试
CREATE TABLE IF NOT EXISTS `user`
(
    `id`     INT(11) AUTO_INCREMENT PRIMARY KEY,
    `name`   VARCHAR(50)  NOT NULL COMMENT '用户姓名',
    `gender` TINYINT(1)   NULL COMMENT '用户性别',
    `age`    INT(3)       NULL COMMENT '用户年龄',
    `info`   VARCHAR(500) NULL COMMENT '用户信息'
)
    COMMENT '用户表';

4.1 DML方法

概念:

  • insert():缺省字段注入null,无主键回注,静态SQL。
  • insertSelective():缺省字段被忽略,无主键回注,动态SQL。
  • updateByPrimaryKey():按主键修改,缺省字段注入null,静态SQL。
  • updateByPrimaryKeySelective():按主键修改,缺省字段被忽略,动态SQL。
  • updateByExample(XXXExample example):按条件修改,缺省字段注入null,静态SQL:
    • example.createCriteria().条件():设置and条件。
    • example.or().条件():设置or条件。
  • updateByExampleSelective(XXXExample example):按条件修改,缺省字段被忽略,动态SQL。
  • deleteByPrimaryKey():按主键删除信息。
  • deleteByExample(XXXExample example):按条件删除信息。

源码: /mybatis3-generator/

  • tst: c.y.generator.UserTest.insert()
package com.yap.generator;

import com.yap.generator.mapper.UserMapper;
import com.yap.generator.pojo.User;
import com.yap.generator.pojo.UserExample;
import com.yap.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

/**
 * @author yap
 */
public class UserTest {

    private SqlSessionFactory factory = MyBatisUtil.getFactory("mybatis-generator.xml");

    /**
     * insert into user (id, name, age, gender, info) values (?, ?, ?, ?, ?)
     * insert into user (name, age) values (?, ?)
     */
    @Test
    public void insert() {
        User liuneng = new User(null, "刘能", null, 58, null);
        User dajiao = new User(null, "大脚", null, 18, null);
        SqlSession session = factory.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.insert(liuneng);
            userMapper.insertSelective(dajiao);
            session.commit();
            System.out.println(liuneng);
            System.out.println(dajiao);
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
  • tst: c.y.generator.UserTest.updateByPrimaryKey()
 /**
     * update user set id = ?, name = ?, gender = ?, age = ?, info = ? where id = ?
     * update user set name = ? where id = ?
     */
    @Test
    public void updateByPrimaryKey() {
        SqlSession session = factory.openSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.updateByPrimaryKey(new User(12, "刘能2", null, null, null));
            userMapper.updateByPrimaryKeySelective(new User(13, "大脚2", null, null, null));
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
  • tst: c.y.generator.UserTest.updateByExample()
 /**
     * update user set gender = 1 where name like '赵%' and gender <> 1
     */
    @Test
    public void updateByExample() {
        SqlSession session = factory.openSession();
        try {
            UserExample example = new UserExample();
            example.createCriteria().andNameLike("赵%").andGenderNotEqualTo(1);
            session.getMapper(UserMapper.class).updateByExampleSelective(
                    new User(null, null, 1, null, null), example);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
  • tst: c.y.generator.UserTest.deleteByPrimaryKey()
 /**
     * delete from user where id = ?
     */
    @Test
    public void deleteByPrimaryKey() {
        SqlSession session = factory.openSession();
        try {
            session.getMapper(UserMapper.class).deleteByPrimaryKey(11);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
  • tst: c.y.generator.UserTest.deleteByExample()
/**
     * delete from user where age is null or age not between 1 and 150
     */
    @Test
    public void deleteByExample() {
        SqlSession session = factory.openSession();
        try {
            UserExample example = new UserExample();
            example.or().andAgeIsNull();
            example.or().andAgeNotBetween(1, 150);
            // if(example != null)
            session.getMapper(UserMapper.class).deleteByExample(example);
            session.commit();
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

4.2 DQL方法

概念:

  • selectByPrimaryKey():通过主键查询信息。
  • selectByExample(XXXExample example):通过条件查询符合的信息,空对象视为全查:
    • example.setOrderByClause():对结果集进行排序。
    • example.setDistinct():对结果集去重。
  • countByExample(XXXExample example):通过条件查询符合的条目数。

源码: /mybatis3-generator/

  • tst: c.y.generator.UserTest.selectByPrimaryKey()
/**
     * select id, name, gender, age, info from user where id = ?
     */
    @Test
    public void selectByPrimaryKey() {
        try (SqlSession session = factory.openSession()) {
            System.out.println(session.getMapper(UserMapper.class).selectByPrimaryKey(7));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  • tst: c.y.generator.UserTest.selectByExample()
 /**
     * select id, name, gender, age, info from user where name like '赵%' and gender = 1
     * select id, name, gender, age, info from user
     */
    @Test
    public void selectByExample() {
        try (SqlSession session = factory.openSession()) {
            UserExample example = new UserExample();
            example.createCriteria().andNameLike("赵%").andGenderEqualTo(1);
            System.out.println(session.getMapper(UserMapper.class).selectByExample(example));
            System.out.println(session.getMapper(UserMapper.class).selectByExample(new UserExample()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • tst: c.y.generator.UserTest.setOrderByClause()
/**
     * select id, name, gender, age, info from user order by age desc
     */
    @Test
    public void setOrderByClause() {
        try (SqlSession session = factory.openSession()) {
            UserExample example = new UserExample();
            example.setOrderByClause("age desc");
            System.out.println(session.getMapper(UserMapper.class).selectByExample(example));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • tst: c.y.generator.UserTest.setDistinct()
/**
     * select distinct id, name, gender, age, info from user
     */
    @Test
    public void setDistinct() {
        try (SqlSession session = factory.openSession()) {
            UserExample example = new UserExample();
            example.setDistinct(true);
            System.out.println(session.getMapper(UserMapper.class).selectByExample(example));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • tst: c.y.generator.UserTest.countByExample()
 /**
     * select count(*) from user where id >= 2
     */
    @Test
    public void countByExample() {
        try (SqlSession session = factory.openSession()) {
            UserExample example = new UserExample();
            example.createCriteria().andIdGreaterThanOrEqualTo(2);
            System.out.println(session.getMapper(UserMapper.class).countByExample(example));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }