tk.mybatis使用方法

本文参考了:

https://www.cnblogs.com/zkm1992/p/10939730.html

https://www.jianshu.com/p/336c71c68a52

引入依赖

使用的版本取决于 SpringBoot 的版本,因为存在兼容性的问题,版本需要提前确认好。

    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper</artifactId>
        <version>4.0.4</version>
    </dependency>

增加 mapper 组件扫描配置

 

/**
 * @author zkm
 * @date 2019/5/19 18:29
 */
@Configuration
@tk.mybatis.spring.annotation.MapperScan("top.zhangsanwan.eat.repository")
@EnableTransactionManagement
public class DalConfig {
} 

创建 dao 层的 base 接口

 

注意:这个 Base 接口一定不要放在 repository 包下面,换言之就是不要被上面的 Mapper 组件扫描配置给扫描到!

创建 BaseRepository<T> 继承 3 个 tk.mybatis.mapper 下的接口:

  1. Mapper<T>
  2. IdsMapper<T>
  3. InsertListMapper<T>

当然如果数据库是用的 mysql,也可以继承如下几个接口:

  1. Mapper<T>
  2. MysqlMapper<T>
public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

public interface MySqlMapper<T> extends InsertListMapper<T>, InsertUseGeneratedKeysMapper<T> {
}

创建 dao 层查询接口

创建 Dao 查询接口 MenuRepository,继承 Dao 层的 Base 接口 BaseRepository,泛型为数据库表对应的映射类。

/**
 * @author zkm
 * @date 2019/5/19 18:24
 */
public interface MenuRepository extends BaseRepository<Menu> {
}

service 调用 dao 层进行查询

/**
 * @author zkm
 * @date 2019/5/19 18:23
 */
@Service
public class MenuServiceImpl implements IMenuService {
@Resource
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> MenuRepository menuRepository;

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> List&lt;MenuVO&gt;<span style="color: rgba(0, 0, 0, 1)"> getMenu(String date) {
    SimpleDateFormat format </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> SimpleDateFormat("yyyy-MM-dd"<span style="color: rgba(0, 0, 0, 1)">);
    String today </span>= StringUtils.isEmpty(date) ? format.format(<span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Date()) : date;
    Example example </span>= <span style="color: rgba(0, 0, 255, 1)">new</span> Example(Menu.<span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">);
    example.createCriteria().andGreaterThanOrEqualTo(</span>"createAt", today + " 00:00:00"<span style="color: rgba(0, 0, 0, 1)">)
            .andLessThanOrEqualTo(</span>"createAt", today + " 23:59:59"<span style="color: rgba(0, 0, 0, 1)">);
    example.setOrderByClause(</span>"sort asc"<span style="color: rgba(0, 0, 0, 1)">);
    List</span>&lt;Menu&gt; menuList =<span style="color: rgba(0, 0, 0, 1)"> menuRepository.selectByExample(example);
    List</span>&lt;MenuVO&gt; menuVOList =<span style="color: rgba(0, 0, 0, 1)"> Lists.newArrayList();
    menuList.forEach(menu </span>-&gt;<span style="color: rgba(0, 0, 0, 1)"> {
        MenuVO menuVO </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> MenuVO();
        BeanUtils.copyProperties(menu, menuVO);
        menuVOList.add(menuVO);
    });
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> menuVOList;
}

}

实体类

Menu 类

public class Menu {
@Id
@Column(name </span>= "id"<span style="color: rgba(0, 0, 0, 1)">)
@GeneratedValue(generator </span>= "JDBC"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> Long id;

@Column(name </span>= "menu_name"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> String menuName;

@JsonFormat(pattern </span>= "yyyy-MM-dd HH🇲🇲ss", timezone = "GMT+8"<span style="color: rgba(0, 0, 0, 1)">)
@DateTimeFormat(pattern </span>= "yyyy-MM-dd HH🇲🇲ss"<span style="color: rgba(0, 0, 0, 1)">)
@Column(name </span>= "create_time"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> Date createTime;

@Column(name </span>= "create_user"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> String createUser;

}

基础接口

Insert

1.InsertMapper<T>

接口:InsertMapper<T>
方法:int insert(T record);
说明:保存一个实体,null 的属性也会保存,不会使用数据库默认值

public int insertTestUser(TestUser testUser) {
    return testUserMapper.insert(testUser);
}

结果:

 

2.InsertSelectiveMapper<T>

接口:InsertSelectiveMapper<T>
方法:int insertSelective(T record);
说明:保存一个实体,null 的属性不会保存,会使用数据库默认值

Update

1.UpdateByPrimaryKeyMapper<T>

接口:UpdateByPrimaryKeyMapper<T>
方法:int updateByPrimaryKey(T record);
说明:根据主键更新实体全部字段,null 值会被更新

结果:
会把没有值的属性变成空请自行实验

2.UpdateByPrimaryKeySelectiveMapper<T>

接口:UpdateByPrimaryKeySelectiveMapper<T>
方法:int updateByPrimaryKeySelective(T record);
说明:根据主键更新属性不为 null 的值

public int updateTestUser() {
        TestUser testUser=new TestUser();
        testUser.setId("5f7139ef295d42a3b964c082e0dd838f");
        testUser.setName("李四四");
        return testUserMapper.updateByPrimaryKeySelective(testUser);
}

结果:

 

Delete

1.DeleteMapper<T>

接口:DeleteMapper<T>
方法:int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号

    public int deleteTestUser() {
        TestUser testUser=new TestUser();
        //根据属性删除会把所有密码是 123456 的数据删除
        testUser.setPassword("123456");
        return testUserMapper.delete(testUser);
    }

结果:
四个已经全部删除

 

2.DeleteByPrimaryKeyMapper<T>

接口:DeleteByPrimaryKeyMapper<T>
方法:int deleteByPrimaryKey(Object key);
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性

   public int deleteKeyTestUser() {
        //根据主键 ID 删除
        return testUserMapper.deleteByPrimaryKey("5f7139ef295d42a3b964c082e0dd838f");}

结果:

 

Select

1.SelectMapper<T>

接口:SelectMapper<T>
方法:List<T> select(T record);
说明:根据实体中的属性值进行查询,查询条件使用等号

    public List<TestUser> selectTestUser() {
        TestUser testUser=new TestUser();
        testUser.setPassword("123456");
        testUser.setUsername("lisi");
        return testUserMapper.select(testUser);
    }

结果:

2.SelectByPrimaryKeyMapper<T>

接口:SelectByPrimaryKeyMapper<T>
方法:T selectByPrimaryKey(Object key);
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号

结果:
根据主键查询请自行实验

3.SelectAllMapper<T>

接口:SelectAllMapper<T>
方法:List<T> selectAll();
说明:查询全部结果,select(null) 方法能达到同样的效果

结果:
查询所有请自行实验

4.SelectOneMapper<T>

接口:SelectOneMapper<T>
方法:T selectOne(T record);
说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号

    public TestUser selectOneTestUser() {
        TestUser testUser=new TestUser();
        testUser.setUsername("wangwu");
        //结果只能返回一条数据否则会抛出异常
        return testUserMapper.selectOne(testUser);
    }

结果:

 

5.SelectCountMapper<T>

接口:SelectCountMapper<T>
方法:int selectCount(T record);
说明:根据实体中的属性查询总数,查询条件使用等号

结果:
返回查询个数请自行实验

Example 方法

Select 方法

1.SelectByExampleMapper<T>

接口:SelectByExampleMapper<T>
方法:List<T> selectByExample(Object example);
说明:根据 Example 条件进行查询
重点:这个查询支持通过 Example 类指定查询列,通过 selectProperties 方法指定查询列

    public List<TestUser> selectExample() {
        Example example = new Example(TestUser.class);
        //排序方法 setOrderByClause("字段名 ASC")DESC 降序
        example.setOrderByClause("name ASC");
        example.createCriteria()
        //添加 xxx 字段等于 value 条件
        .andEqualTo("password","123456")
        //模糊查询 xxx 字段 like value 条件
        .andLike("name","% 四 %")
         //可以自由拼接 SQL
        //.andCondition("ID ='5f7139ef295d42a3b964c082e0dd838f' ")
         //或者可以这么写
        .andCondition("ID =","5f7139ef295d42a3b964c082e0dd838f")
        ;
        return testUserMapper.selectByExample(example);
    }

实例解析:

mybatis 的逆向工程中会生成实例及实例对应的 example,example 用于添加条件,相当 where 后面的部分
Example example = new Example();
Criteria criteria = example.createCriteria();

 

还有 criteria.orxxxx 的方法跟上面一样这里不做解释

2. SelectCountByExampleMapper<T>

接口:SelectCountByExampleMapper<T>
方法:int selectCountByExample(Object example);
说明:根据 Example 条件进行查询总数

查询总数的方法跟上面的写法一样

Update 方法

1.UpdateByExampleMapper<T>

接口:UpdateByExampleMapper<T>
方法:int updateByExample(@Param("record") T record, @Param("example") Object example);
说明:根据 Example 条件更新实体 record 包含的全部属性,null 值会被更新

2.UpdateByExampleSelectiveMapper<T>

接口:UpdateByExampleSelectiveMapper<T>
方法:int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
说明:根据 Example 条件更新实体 record 包含的不是 null 的属性值

Delete 方法

1.DeleteByExampleMapper<T>

接口:DeleteByExampleMapper<T>
方法:int deleteByExample(Object example);
说明:根据 Example 条件删除数据

搭配手写 sql

tk.mybatis 对于单表操作可以避免手写 sql,但是业务中一些复杂 sql 肯定是必不可少的,那么 tk.mybatis 也支持。

首先看下 tk.mybatis 的依赖

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>

mapper-spring-boot-starter.jar 同时依赖了 org.mybatis

application.yml

# MyBatis 配置
mybatis:
  # 搜索指定包别名
  typeAliasesPackage: com.yzf.enterprise.market.**.domain
  # 配置 mapper 的扫描,找到所有的 mapper.xml 映射文件
  mapperLocations: classpath*:mybatis/**/*Mapper.xml
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml

@MapperScan----- 扫描所有的 Mapper 接口

@MapperScan("com.yzf.enterprise.market.**.mapper")

Mapper 接口

@Repository
public interface WxUserInfoMapper extends Mapper<WxUserInfo>, MySqlMapper<WxUserInfo> {
</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * 保存微信用户相关信息
 * </span><span style="color: rgba(128, 128, 128, 1)">@param</span><span style="color: rgba(0, 128, 0, 1)"> wxUserInfo
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> saveWxUserInfo(WxUserInfo wxUserInfo);

}

mapper.xml

我上面配置的 xml 文件地址为:mapperLocations: classpath*:mybatis/**/*Mapper.xml

 

因此 xml 文件放在这个位置。 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yzf.enterprise.market.project.weixin.mapper.WxUserInfoMapper">
<resultMap type="com.yzf.enterprise.market.project.weixin.domain.WxUserInfo" id="WxUserInfoResult">
<id property="userId" column="id"/>
<result property="unionId" column="union_id"/>
<result property="openId" column="open_id"/>
<result property="status" column="status"/>
</resultMap>

<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> unionId字段为唯一索引,因此存在unionId,就更新;不存在,则插入 </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">insert </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="saveWxUserInfo"</span><span style="color: rgba(255, 0, 0, 1)"> useGeneratedKeys</span><span style="color: rgba(0, 0, 255, 1)">="true"</span><span style="color: rgba(255, 0, 0, 1)"> keyProperty</span><span style="color: rgba(0, 0, 255, 1)">="id"</span><span style="color: rgba(255, 0, 0, 1)">
        parameterType</span><span style="color: rgba(0, 0, 255, 1)">="com.yzf.enterprise.market.project.weixin.domain.WxUserInfo"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    insert into wx_user_info(
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">if </span><span style="color: rgba(255, 0, 0, 1)">test</span><span style="color: rgba(0, 0, 255, 1)">="unionId != null and unionId != ''"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        union_id,
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">if</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">if </span><span style="color: rgba(255, 0, 0, 1)">test</span><span style="color: rgba(0, 0, 255, 1)">="openId != null and openId != ''"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        open_id,
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">if</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    create_time
    )values
    (
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">if </span><span style="color: rgba(255, 0, 0, 1)">test</span><span style="color: rgba(0, 0, 255, 1)">="unionId != null and unionId != ''"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        #{unionId},
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">if</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">if </span><span style="color: rgba(255, 0, 0, 1)">test</span><span style="color: rgba(0, 0, 255, 1)">="openId != null and openId != ''"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        #{openId},
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">if</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    sysdate()
    )
    on duplicate key update
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">if </span><span style="color: rgba(255, 0, 0, 1)">test</span><span style="color: rgba(0, 0, 255, 1)">="openId != null and openId != ''"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
        open_id = #{openId},
    </span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">if</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span><span style="color: rgba(0, 0, 0, 1)">
    update_time = now()
</span><span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">insert</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</mapper>