溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

TKMybatis的使用方法是什么

發(fā)布時間:2021-12-01 13:34:18 來源:億速云 閱讀:231 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“TKMybatis的使用方法是什么”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

一、什么是 TKMybatis

TKMybatis 是基于 Mybatis 框架開發(fā)的一個工具,內(nèi)部實(shí)現(xiàn)了對單表的基本數(shù)據(jù)操作,只需要簡單繼承 TKMybatis 提供的接口,就能夠?qū)崿F(xiàn)無需編寫任何 sql 即能完成單表操作。

二、TKMybatis 使用

2.1 Springboot 項(xiàng)目中加入依賴

<!--通用mapper起步依賴-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.4</version>
</dependency>

在 POJO 類中加入依賴

<!--每個工程都有Pojo,都需要用到該包對應(yīng)的注解-->
<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
    <scope>compile</scope>
</dependency>

在啟動類中配置 @MapperScan 掃描

@SpringBootApplication
@MapperScan(basePackages = {"com.tom.order.mapper"})
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}

2.2 使用講解

2.2.1 實(shí)體類中使用

在實(shí)體類中,常用的注解和意義為:

@Table:描述數(shù)據(jù)庫表信息,主要屬性有name(表名)、schema、catalog、uniqueConstraints等。

@Id:指定表主鍵字段,無屬性值。

@Column:描述數(shù)據(jù)庫字段信息,主要屬性有name(字段名)、columnDefinition、insertable、length、nullable(是否可為空)、precision、scale、table、unique、updatable等。

@ColumnType:描述數(shù)據(jù)庫字段類型,可對一些特殊類型作配置,進(jìn)行特殊處理,主要屬性有jdbcType、column、typeHandler等。

其他注解如:@Transient、@ColumnResult、@JoinColumn、@OrderBy、@Embeddable等暫不描述

2.2.2 dao中使用

單表操作,只需要繼承 tk.mybatis 下的 Mapper 接口即可使用

import tk.mybatis.mapper.common.Mapper;
 
@Repository
public interface BrandMapper extends Mapper<Brand> {
}

查看具體使用:內(nèi)部都已經(jīng)封裝了基本的單表操作

TKMybatis的使用方法是什么TKMybatis的使用方法是什么

 2.2.3 Service 層中使用

操作類型介紹
增加Mapper.insert(record);保存一個實(shí)體,null的屬性也會保存,不會使用數(shù)據(jù)庫默認(rèn)值
Mapper.insertSelective(record);保存一個實(shí)體,忽略空值,即沒提交的值會使用使用數(shù)據(jù)庫默認(rèn)值

刪除Mapper.delete(record);根據(jù)實(shí)體屬性作為條件進(jìn)行刪除,查詢條件使用等號
Mapper.deleteByExample(example)根據(jù)Example條件刪除數(shù)據(jù)
Mapper.deleteByPrimaryKey(key)根據(jù)主鍵字段進(jìn)行刪除,方法參數(shù)必須包含完整的主鍵屬性

修改Mapper.updateByExample(record,example)根據(jù)Example條件更新實(shí)體`record`包含的全部屬性,null值會被更新
Mapper.updateByExampleSelective(record, example)根據(jù)Example條件更新實(shí)體`record`包含的不是null的屬性值
Mapper.updateByPrimaryKey(record)根據(jù)主鍵更新實(shí)體全部字段,null值會被更新
Mapper.updateByPrimaryKeySelective(record)根據(jù)主鍵更新屬性不為null的值

查詢Mapper.select(record)根據(jù)實(shí)體中的屬性值進(jìn)行查詢,查詢條件使用等號
Mapper.selectAll()查詢?nèi)拷Y(jié)果
Mapper.selectByExample(example)根據(jù)Example條件進(jìn)行查詢
Mapper.selectByPrimaryKey(key)根據(jù)主鍵字段進(jìn)行查詢,方法參數(shù)必須包含完整的主鍵屬性,查詢條件使用等號
Mapper.selectCount(record)根據(jù)實(shí)體中的屬性查詢總數(shù),查詢條件使用等號
Mapper.selectCountByExample(example)根據(jù)Example條件進(jìn)行查詢總數(shù)
Mapper.selectOne(record)

根據(jù)實(shí)體中的屬性進(jìn)行查詢,只能有一個返回值,有多個結(jié)果是拋出異常,查詢條件使用等號。

但是如果存在某個屬性為int,則會初始化為0??赡苡绊懙綄?shí)際使用

2.3 實(shí)際案例

2.3.1 dao 層使用

 import tk.mybatis.mapper.common.Mapper;
 
/**
 * DAO 使用通用Mapper
 * DSO接口需要繼承 tk.mybatis.mapper.common.Mapper
 */
@Repository
public interface BrandMapper extends Mapper<Brand> {
 
 
}

2.3.2 service 層使用

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
 
import java.util.List;
 
@Service
public class BrandServiceImpl implements BrandService {
 
    @Autowired
    private BrandMapper brandMapper;
 
    public Example createExample(Brand brand) {
        // 自定義條件搜索對象 Example
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria(); //條件構(gòu)造器
 
        if (brand != null) {
            if (!StringUtils.isEmpty(brand.getName())) {
                criteria.andLike("name", '%' + brand.getName() + '%');
            }
 
            if (!StringUtils.isEmpty(brand.getLetter())) {
                criteria.andEqualTo("letter", brand.getLetter());
            }
        }
        return example;
    }
 
    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }
 
    @Override
    public List<Brand> findList(Brand brand) {
        Example example = createExample(brand);
        return brandMapper.selectByExample(example);
    }
 
    @Override
    public Brand findById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }
 
    /**
     * 分頁查詢
     * @param page  當(dāng)前頁
     * @param size  每頁顯示的條數(shù)
     * @return
     */
    @Override
    public PageInfo<Brand> pageSearch(Integer page, Integer size) {
        // 分頁實(shí)現(xiàn)
        // 后面的查詢必須是緊跟集合查詢
        PageHelper.startPage(page, size);
        // 查詢集合
        List<Brand> brands = brandMapper.selectAll();
        return new PageInfo<Brand>(brands);
    }
 
    @Override
    public PageInfo<Brand> pageSearchAndCondition(Brand brand, Integer page, Integer size) {
        // 開始分頁
        PageHelper.startPage(page, size);
        // 搜索數(shù)據(jù)
        Example example = createExample(brand);
        List<Brand> list = brandMapper.selectByExample(example);
        return new PageInfo<Brand>(list);
    }
 
    /**
     * 增加品牌
     * @param brand
     */
    @Override
    public void add(Brand brand) {
        // 使用通用 Mapper.insertSelective
        // 方法中但凡帶有selective就會忽略空值
        int i = brandMapper.insertSelective(brand);
    }
 
    /**
     * 根據(jù)id修改品牌
     * @param brand
     */
    @Override
    public void update(Brand brand) {
        // 使用通用mapper.update();
        brandMapper.updateByPrimaryKeySelective(brand);
    }
 
    /**
     * 根據(jù)id刪除
     * @param id
     */
    @Override
    public void del(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
    }
}

三、擴(kuò)展介紹

使用

public interface BaseMapper<T> extends tk.mybatis.mapper.common.BaseMapper<T>, IdsMapper<T>, MySqlMapper<T>, OracleMapper<T> {
}

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

注:為了演示所以同時引用了MySqlMapper和OracleMapper 正常情況是只能引用一種因?yàn)樗麄冇幸粋€相同的方法insertList(List list)

泛型(實(shí)體類)的類型必須符合要求

實(shí)體類按照如下規(guī)則和數(shù)據(jù)庫表進(jìn)行轉(zhuǎn)換,注解全部是JPA中的注解:

  • 表名默認(rèn)使用類名,駝峰轉(zhuǎn)下劃線(只對大寫字母進(jìn)行處理),如UserInfo默認(rèn)對應(yīng)的表名為user_info。

  • 表名可以使用@Table(name = “tableName”)進(jìn)行指定,對不符合第一條默認(rèn)規(guī)則的可以通過這種方式指定表名。

  • 字段默認(rèn)和@Column一樣,都會作為表字段,表字段默認(rèn)為Java對象的Field名字駝峰轉(zhuǎn)下劃線形式。

  • 可以使用@Column(name = “fieldName”)指定不符合第3條規(guī)則的字段名。

  • 使用@Transient注解可以忽略字段,添加該注解的字段不會作為表字段使用。

  • 建議一定是有一個@Id注解作為主鍵的字段,可以有多個@Id注解的字段作為聯(lián)合主鍵。

所有的mapper繼承此類將具有以下通用方法

查詢方法

BaseSelectMapper下的通用方法

方法名稱作用
List selectAll();查詢?nèi)繑?shù)據(jù)
T selectByPrimaryKey(Object key);通過主鍵查詢
T selectOne(T record);通過實(shí)體查詢單個數(shù)據(jù)
List select(T record);通過實(shí)體查詢多個數(shù)據(jù)
int selectCount(T record);通過實(shí)體查詢實(shí)體數(shù)量
boolean existsWithPrimaryKey(Object key);通過主鍵查詢此主鍵是否存在

SelectByIdsMapper下的通用方法

方法名稱作用
List selectByIds(String var1);通過多個主鍵查詢數(shù)據(jù)

添加方法
BaseInsertMapper下的通用方法

方法名稱作用
int insert(T record);全部添加
int insertSelective(T record);選擇性(不為null)的添加

MySqlMapper下的通用方法

方法名稱作用
int insertList(List list);批量插入
int insertUseGeneratedKeys(T record);如果主鍵為自增可使用此方法獲取添加成功的主鍵

OracleMapper下的通用方法

方法名稱作用
int insertList(List list);批量插入

修改方法

BaseUpdateMapper下的通用方法

方法名稱作用
int updateByPrimaryKey(T record);按照實(shí)體進(jìn)行修改
int updateByPrimaryKeySelective(T record);按照實(shí)體進(jìn)行有選擇的修改

刪除方法
BaseDeleteMapper下的通用方法

方法名稱作用
int delete(T record);按照實(shí)體進(jìn)行刪除
int deleteByPrimaryKey(Object o);按照主鍵進(jìn)行刪除

IdsMapper下的通用方法

方法名稱作用
int deleteByIds(String var1);按照主鍵批量刪除

“TKMybatis的使用方法是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI