tkmapper教程_tkmapper

tkmapper教程_tkmapperTKmapper初学springboot的集成,方式分为两大类:基于starter的自动配置基于@MapperScan注解的手工配置在starter的逻辑中,如果你没有使用@MapperScan注解,你就需要在你的接口上增加@Mapper注解,否则MyBatis无法判断扫描哪些接口。<dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spri

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

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 属性。 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/185065.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • python的sorted函数「建议收藏」

    python的sorted函数「建议收藏」sorted很简单,没太多好写的,只是给自己做个笔记。sorted接受三个参数,返回一个排序之后的list。第一个接受一个可迭代的对象(因为sorted实现了迭代协议,所以接受的参数不一定需要l

  • BYTE 和 COleVariant 相互转换

    BYTE 和 COleVariant 相互转换#include     BOOL GetBinaryFromVariant(COleVariant & ovData, BYTE ** ppBuf, unsigned long * pcBufLen)  {    BOOL fRetVal = FALSE;      //Binary data is stored in the variant as an array of

  • VS2010的详细安装[通俗易懂]

    VS2010的详细安装[通俗易懂]MicrosoftVisualStudio2010旗舰版的详细安装。安装包:链接:https://pan.baidu.com/s/1-JNyGhwIvasAYQL0GsmzQw密码:fddsstep1、拷贝或下载的安装包(MicrosoftVisualStudio2010.rar)放在E盘(最好不要放在C盘)——&gt;softs——&gt;vs2010——&gt;右击安装…

  • JAVA——数组截取——调用库中方法

    JAVA——数组截取——调用库中方法1,使用Java类库中的方法System.arraycopy2,使用Java类库中的方法java.util.Arrays.copyOf3,重写myCopy(一)使用.arraycopy方法使用方法:System.arraycopy(源数组名称,源数组开始点,目标数组名称,目标数组开始点,拷贝长度);说明:将arr1数组中的一部分替换成arr2数组中的一部分可以从任意位置开始截取…

  • 91p.wido.ws_tttzzzvipAPP

    91p.wido.ws_tttzzzvipAPP104.27.179.100北美地区IP网段:104.16.0.0-104.31.255.255更新时间:2014年07月19日18:47:41NetRange:104.16.0.0-104.31.255.255CIDR:104.16.0.0/12OriginAS:AS13335NetName:CLOUDFLARENETNetHandle:NET-104-16-0-0-1P…

    2022年10月30日
  • vuecli3配置webpack_vue不混淆如何配置

    vuecli3配置webpack_vue不混淆如何配置前言如果我们想在webpack中使用vue,就需要在webpack中配置vue配置vue首先,我们需要在项目中安装vue,安装命令如下:npminstallvue–save安装完成后

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号