日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

通用mapper的查詢,selectByPrimaryKey、select、selectByExample等

作者:Pisces_224 更新時間: 2022-02-27 編程語言

最近有在用到mybatis的通用mapper的查詢,既然接觸了索性記錄總結一下,以便幫到后來人。

一. 首先,放上mybatis 通用mapper的接口代碼Mapper.class:

package tk.mybatis.mapper.common;

import tk.mybatis.mapper.annotation.RegisterMapper;

@RegisterMapper
public interface Mapper<T> extends BaseMapper<T>, ExampleMapper<T>, RowBoundsMapper<T>, Marker {
}

對于我們項目來說,很多對數據庫表的自定義mapper映射都是繼承自通用Mapper的,要想繼承,就必須指定泛型。

拿我項目來舉例子:假設我有一實體類 Student.java,與我數據庫里的Student表屬性、字段一一對應,那么我想使用通用Mapper的各種方法,就要這么實現:
在mapper文件夾下新建StudentMapper.java文件,代碼如下:

package com.project.business.mapper;


import com.project.common.model.business.Student;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.common.Mapper;

/**
 * @Author cyl
 * @Date 2021/10/15 09:55
 * @Version 1.0
 **/
@Component
public interface StudentMapper extends Mapper<Student> {
}

二. 在自己的service目錄下定義好service以及serviceIml實現,在實現類中通過注解@Autowired注入StudentMapper對象作為屬性;然后在類中的方法里便可以使用通用mapper的各類方法了。

@Transactional
@Service
public class StudentServiceImpl implements StudentService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StudentMapper studentMapper;

	@Override
    public StudentVO findInfo(String s_id) throws BusinessException
    {}

2.1 selectByPrimaryKey()主鍵查詢

使用主鍵查詢時,要注意幾個地方:

  • 主鍵只有一個,多個不起作用;
  • 待查詢的主鍵,在***對應實體類屬性上必須標有 @Id***,該方法才能識別它為主鍵且按照主鍵去查詢,否則只會將所有字段作為聯合主鍵來查詢!

具體使用:

Student student = studentMapper.selectByPrimaryKey(s_id);
if(student == null) {
            throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR, s_id + " 該學生不存在");
        }

2.2 非主鍵字段使用selectByExample()查詢

當我想查詢的字段不是主鍵時,可以調用selectByExample()方法:

Example o = new Example(Student.class);
Example.Criteria criteria = o.createCriteria();
o.setOrderByClause("s_score desc");   // 查詢條件按成績降序排序
criteria.andLike("s_name","%"+s_name+"%");  // 按名字模糊查詢
criteria.andNotEqualTo("deleted",1);  // 查詢未被刪除的學生(deleted 1為已被刪除)

List<Student> students= studentMapper.selectByExample(o);  // 普通查詢
logger.info("query result students size: " + students.size());

if(students.size() > 0) {
    logger.info(" result s_id: " + students.get(0).getS_id());
        }

對于Example的解釋:
Mybatis的逆向工程中會生成實例及實例對應的Example,Example用于添加條件,等同于SQL語句WHERE關鍵字后的篩選條件部分。


以上僅記錄主鍵查詢和普通查詢實例,更多詳細增刪改查等方法使用看
另外一篇文章專門記錄通用mapper常用函數以及Example常用篩選條件:

傳送門:通用mapper常用函數總結

參考博客:

  1. Mybatis通用Mapper使用詳解:https://www.jianshu.com/p/5854bfd0f0e6

原文鏈接:https://blog.csdn.net/qq_36256590/article/details/121436404

欄目分類
最近更新