tkmapper教程_tkmapper
大家好,又見面了,我是你們的朋友風君子。如果您正在找激活碼,請點擊查看最新教程,關注關注公眾號 “全棧程序員社區” 獲取激活教程,可能之前舊版本教程已經失效.最新Idea2022.1教程親測有效,一鍵激活。
Jetbrains全系列IDE穩定放心使用
TK mapper初學
springboot的集成,方式分為兩大類:
- 基于 starter 的自動配置
- 基于
@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,catalog 和 schema 三個屬性,配置 name 屬性后,直接使用提供的表名,不再根據實體類名進行轉換。
@Table(name = "sys_user") //將 User 實體映射到 sys_user 表
public class User
@Column 注解(JPA)
@Column 注解支持 name, insertable 和 updateable 三個屬性。
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
同catalog,catalog優先級高于schema。
notEmpty
insertSelective 和 updateByPrimaryKeySelective 中,是否判斷字符串類型 !=''。
//配置方式:
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 屬性。
總結
以上是生活随笔為你收集整理的tkmapper教程_tkmapper的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习模型的性能指标
- 下一篇: 仅20天!全国快递业揽收包裹39.4亿件