TKmapper初识

TK mapper初学

springboot的集成,方式分为两大类:
  1. 基于 starter 的自动配置
  2. 基于 @MapperScan 注解的手工配置

在 starter 的逻辑中,如果你没有使用 @MapperScan 注解,你就需要在你的接口上增加 @Mapper 注解,否则 MyBatis 无法判断扫描哪些接口。

<dependency>
  <groupId>tk.mybatis</groupId>
  <artifactId>mapper-spring-boot-starter</artifactId>
  <version>版本号</version>
</dependency>

@MapperScan 注解配置可以给带有 @Configuration 的类配置该注解,或者直接配置到 Spring Boot 的启动类上,如下:

@tk.mybatis.spring.annotation.MapperScan(basePackages = "扫描包")
@SpringBootApplication
public class SampleMapperApplication implements CommandLineRunner {

注意:引入该 starter 时,和 MyBatis 官方的 starter 没有冲突,但是官方的自动配置不会生效!

可以对通用mapper进行yml配置:

mapper:
  mappers:
    - tk.mybatis.mapper.common.Mapper
    - tk.mybatis.mapper.common.Mapper2
  notEmpty: true
@NameStyle 注解(Mapper)

这个注解可以在类上进行配置,优先级高于对应的 style 全局配置。

normal,                     //原值
camelhump,                  //驼峰转下划线
uppercase,                  //转换为大写
lowercase,                  //转换为小写
camelhumpAndUppercase,      //驼峰转下划线大写形式
camelhumpAndLowercase,      //驼峰转下划线小写形式
@NameStyle(Style.camelhumpAndUppercase)
public class Country   //会将形如 userName 的字段转换为表中的 USER_NAME 字段
@Table 注解(JPA)

@Table 注解可以配置 name,catalogschema 三个属性,配置 name 属性后,直接使用提供的表名,不再根据实体类名进行转换。

@Table(name = "sys_user")  //将 User 实体映射到 sys_user 表
public class User
@Column 注解(JPA)

@Column 注解支持 name, insertableupdateable 三个属性。

name 配置映射的列名。

insertable 对提供的 insert 方法有效,如果设置 false 就不会出现在 SQL 中。

updateable 对提供的 update 方法有效,设置为 false 后不会出现在 SQL 中。

@Column(name = "user_name")  //映射 name 到 user_name
private String name;

// mysql关键字 order 映射
@Column(name = "`order`")
private String order;
@Transient 注解(JPA)
@Transient
private String otherThings; //非数据库表中字段
@Id 注解(JPA)

一个实体类中至少需要一个标记 @Id 注解的字段,存在联合主键时可以标记多个。如果表中没有主键,类中就可以不标记。当类中没有存在标记 @Id 注解的字段时,你可以理解为类中的所有字段是联合主键使用所有的 ByPrimaryKey 相关的方法时,有 where 条件的地方,会将所有列作为条件。

//联合主键
@Id
private Integer userId;
@Id
private Integer roleId;
@KeySql 注解

主键策略注解,用于配置如何生成主键。

这是通用 Mapper 的自定义注解,改注解的目的就是替换 @GeneratedValue 注解。

@Id
@KeySql(useGeneratedKeys = true)
private Long id;

配置介绍

//通用 Mapper 提供了下面这些参数:
mappers
IDENTITY
ORDER(别名: order, before)
catalog
schema
notEmpty
style
enableMethodAnnotation
useSimpleType
usePrimitiveType
simpleTypes
enumAsSimpleType
wrapKeyword
checkExampleEntityClass
safeDelete
safeUpdate
useJavaType
mappers

在 4.0 以前这是一个非常重要的参数,当时只有通过 mappers 配置过的接口才能真正调用,4.0 之后,增加了一个 @RegisterMapper 注解,通用 Mapper 中提供的所有接口都有这个注解,有了该注解后,通用 Mapper 会自动解析所有的接口,如果父接口(递归向上找到的最顶层)存在标记该注解的接口,就会自动注册上。因此 4.0 后使用通用 Mapper 提供的方法时,不需要在配置这个参数。

当你自己扩展通用接口时,建议加上该注解,否则就要配置 mappers 参数。

IDENTITY
//取回主键的方式,列表数据库名字后面对应的 SQL 是插入后取 id 的 SQL 语句。
DB2: VALUES IDENTITY_VAL_LOCAL()
MYSQL: SELECT LAST_INSERT_ID()
SQLSERVER: SELECT SCOPE_IDENTITY()
CLOUDSCAPE: VALUES IDENTITY_VAL_LOCAL()
DERBY: VALUES IDENTITY_VAL_LOCAL()
HSQLDB: CALL IDENTITY()
SYBASE: SELECT @@IDENTITY
DB2_MF: SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
INFORMIX: select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
IDENTITY=MYSQL   //配置
catalog

数据库的catalog,如果设置该值,查询的时候表名会带catalog设置的前缀。

schema

catalogcatalog优先级高于schema

notEmpty

insertSelectiveupdateByPrimaryKeySelective 中,是否判断字符串类型 !=''

//配置方式:
notEmpty=true
enableMethodAnnotation

可以控制是否支持(getter 和 setter)在方法上使用注解,默认false

style
normal:原值
camelhump:驼峰转下划线
uppercase:转换为大写
lowercase:转换为小写
camelhumpAndUppercase:驼峰转下划线大写形式
camelhumpAndLowercase:驼峰转下划线小写形式
useSimpleType

默认 true,启用后判断实体类属性是否为表字段时校验字段是否为简单类型,如果不是就忽略该属性,这个配置优先级高于所有注解。

注意:byte, short, int, long, float, double, char, boolean 由于存在默认值,这里不会作为简单类型对待!也就是默认情况下,这些字段不会和表字段进行映射。

usePrimitiveType

为了方便部分还在使用基本类型的实体,增加了该属性,只有配置该属性,并且设置为 true 才会生效,启用后,会扫描 8 种基本类型。

wrapKeyword

配置后会自动处理关键字,可以配的值和数据库有关。

wrapKeyword=`{0}`   //mysql配置
//使用该配置后,类似 private String order 就不需要通过 @Column 来指定别名。
checkExampleEntityClass
默认 false 用于校验通用 Example 构造参数 entityClass 是否和当前调用的 Mapper<EntityClass> 类型一致。
假设存在下面代码:
Example example = new Example(City.class);
example.xxx...;//设置条件的方法
countryMapper.selectByExample(example);
注意,这里使用 City 创建的 Example,本该使用 cityMapper 来调用,但是这里使用了 countryMapper
配置该字段为 true 后就会对不匹配的情况进行校验!
 checkExampleEntityClass=true
safeDelete\safeUpdate

配置为 true 后,delete 和 deleteByExample 都必须设置查询条件才能删除,否则会抛出异常。

Caused by: tk.mybatis.mapper.MapperException: 通用 Mapper 安全检查: 当前操作的方法没有指定查询条件,不允许执行该操作!

Example

查询
Example example = new Example(Country.class);
example.setForUpdate(true);
example.createCriteria().andGreaterThan("id", 100).andLessThan("id",151);
example.or().andLessThan("id", 41);
List<Country> countries = mapper.selectByExample(example);
//日志
DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( id > ? and id < ? ) or ( id < ? ) ORDER BY id desc FOR UPDATE 
DEBUG [main] - ==> Parameters: 100(Integer), 151(Integer), 41(Integer)
动态sql
Example example = new Example(Country.class);
Example.Criteria criteria = example.createCriteria();
if(query.getCountryname() != null){
    criteria.andLike("countryname", query.getCountryname() + "%");
}
if(query.getId() != null){
    criteria.andGreaterThan("id", query.getId());
}
List<Country> countries = mapper.selectByExample(example);
//日志:
DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( countryname like ? ) ORDER BY id desc 
DEBUG [main] - ==> Parameters: China%(String)
排序
Example example = new Example(Country.class);
example.orderBy("id").desc().orderBy("countryname").orderBy("countrycode").asc();
List<Country> countries = mapper.selectByExample(example);
//日志:
DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country order by id DESC,countryname,countrycode ASC 
DEBUG [main] - ==> Parameters: 
去重
CountryExample example = new CountryExample();
//设置 distinct
example.setDistinct(true);
example.createCriteria().andCountrynameLike("A%");
example.or().andIdGreaterThan(100);
List<Country> countries = mapper.selectByExample(example);
//日志:
DEBUG [main] - ==>  Preparing: SELECT distinct id,countryname,countrycode FROM country WHERE ( countryname like ? ) or ( Id > ? ) ORDER BY id desc 
DEBUG [main] - ==> Parameters: A%(String), 100(Integer)
设置查询的列
Example example = new Example(Country.class);
example.selectProperties("id", "countryname");
List<Country> countries = mapper.selectByExample(example);
//日志:
DEBUG [main] - ==>  Preparing: SELECT id , countryname FROM country ORDER BY id desc 
DEBUG [main] - ==> Parameters: 
Example.builder 方式
Example example = Example.builder(Country.class)
        .select("countryname")
        .where(Sqls.custom().andGreaterThan("id", 100))
        .orderByAsc("countrycode")
        .forUpdate()
        .build();
List<Country> countries = mapper.selectByExample(example);
//日志:
DEBUG [main] - ==>  Preparing: SELECT countryname FROM country WHERE ( id > ? ) order by countrycode Asc FOR UPDATE 
DEBUG [main] - ==> Parameters: 100(Integer)
Weekend
List<Country> selectByWeekendSql = mapper.selectByExample(new Example.Builder(Country.class)
        .where(WeekendSqls.<Country>custom().andLike(Country::getCountryname, "%a%")
                .andGreaterThan(Country::getCountrycode, "123"))
        .build());
//日志:
DEBUG [main] - ==>  Preparing: SELECT id,countryname,countrycode FROM country WHERE ( countryname like ? and countrycode > ? ) 
DEBUG [main] - ==> Parameters: %a%(String), 123(String)

二级缓存

只使用接口

只用接口时,只需要加一个缓存的注解

//只有接口时,加下面的注解即可
@CacheNamespace
public interface CountryCacheMapper extends Mapper<Country> {}
接口和 XML 混合

由于 MyBatis 目前处理 XML 和 接口中的引用时存在 BUG,所以只有这里提供的一种方式进行配置。也就是在 XML 中配置 <cache/>,在接口中使用 @CacheNamespaceRef(CountryCacheRefMapper.class) 引用注解。

//1.在 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="tk.mybatis.mapper.cache.CountryCacheRefMapper">
    <cache/>  //这里配置
    <select id="selectById" resultType="tk.mybatis.mapper.base.Country">
        select * from country where id = #{id}
    </select>
</mapper>
//2.在接口中配置注解引用:接口类名或xml的namespace
@CacheNamespaceRef(CountryCacheRefMapper.class)
//或者 @CacheNamespaceRef(name = "tk.mybatis.mapper.cache.CountryCacheRefMapper")
public interface CountryCacheRefMapper extends Mapper<Country> {
// 定义在 XML 中的方法
    Country selectById(Integer id);
}
//@CacheNamespaceRef 指定的是缓存的 namespace,就是 XML 中 <mapper> 中的 namespace 属性。     
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值