阿里-马云的学习笔记

导航

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
    private MenuRepository menuRepository;

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

实体类

Menu类

public class Menu {

    @Id
    @Column(name = "id")
    @GeneratedValue(generator = "JDBC")
    protected Long id;
    
    @Column(name = "menu_name")
    private String menuName;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @Column(name = "create_time")
    protected Date createTime;

    @Column(name = "create_user")
    protected 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> {

    /**
     * 保存微信用户相关信息
     * @param wxUserInfo
     */
    void 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>

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

 

posted on 2020-03-26 09:44  阿里-马云的学习笔记  阅读(31566)  评论(0编辑  收藏  举报