最近有在用到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常用函数总结
参考博客:
- Mybatis通用Mapper使用详解:https://www.jianshu.com/p/5854bfd0f0e6