一文详解MyBatis的Mapper接口以及Example类

一、基础介绍

1.什么是example类

mybatis-generator会为每个字段产生如上的Criterion,如果表的字段比较多,产生的Example类会十分庞大。理论上通过example类可以构造你想到的任何筛选条件。在mybatis-generator中加以配置,配置数据表的生成操作就可以自动生成example了。具体配置可以参考MBG有关配置
下面是mybatis自动生成example的使用。

2.了解example成员变量

     //升序还是降序
     //参数格式:字段+空格+asc(desc)
     protected String orderByClause;
     //去除重复
     //true是选择不重复记录
     protected boolean distinct;
     //自定义查询条件
     //Criteria的集合,集合中对象是由or连接
     protected List<Criteria> oredCriteria;
     //内部类Criteria包含一个Cretiron的集合,
     //每一个Criteria对象内包含的Cretiron之间
     //是由AND连接的
     public static class Criteria extends GeneratedCriteria {
         protected Criteria() {
             super(); 
         }
     }
     //是mybatis中逆向工程中的代码模型
     protected abstract static class GeneratedCriteria
     {…..}
     //是最基本,最底层的Where条件,用于字段级的筛选
     public static class Criterion {……}

二、mapper接口中的方法解析

Mapper接口中部分方法的解析:

方法 功能说明
int countByExample(UserExample example) thorws SQLException 按条件计数
int deleteByPrimaryKey(Integer id) thorws SQLException 按主键删除
int deleteByExample(UserExample example) thorws SQLException 按条件查询
String/Integer insert(User record) thorws SQLException 插入数据(返回值为ID)
User selectByPrimaryKey(Integer id) thorws SQLException 按主键查询
List selectByExample(UserExample example) thorws SQLException 按条件查询
List selectByExampleWithBLOGs(UserExample example) thorws SQLException 按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。
int updateByPrimaryKey(User record) thorws SQLException 按主键更新
int updateByPrimaryKeySelective(User record) thorws SQLException 按主键更新值不为null的字段
int updateByExample(User record, UserExample example) thorws SQLException 按条件更新
int updateByExampleSelective(User record, UserExample example) thorws SQLException 按条件更新值不为null的字段

三、example实例解析

mybatis的逆向工程中会生成实例及实例对应的example,example用于添加条件,相当where后面的部分

xxxExample example = new xxxExample(); 
Criteria criteria = new Example().createCriteria();

Example的实例函数如下:

方法 说明
example.setOrderByClause(“字段名 ASC”); 添加升序排列条件,DESC为降序
example.setDistinct(false) 去除重复,boolean型,true为选择不重复的记录。
criteria.andIsNull 添加字段为null的条件
criteria.andIsNotNull 添加字段不为null的条件
criteria.andEqualTo(value) 添加字段等于value条件
criteria.andNotEqualTo(value) 添加字段不等于value条件
criteria.andGreaterThan(value) 添加字段大于value条件
criteria.andGreaterThanOrEqualTo(value) 添加字段大于等于value条件
criteria.andLessThan(value) 添加字段小于value条件
criteria.andLessThanOrEqualTo(value) 添加字段小于等于value条件
criteria.andIn(List<?>) 添加字段值在List<?>条件
criteria.andNotIn(List<?>) 添加字段值不在List<?>条件
criteria.andLike(“%”+value+”%”) 添加字段值为value的模糊查询条件
criteria.andNotLike(“%”+value+”%”) 添加字段值不为value的模糊查询条件
criteria.andBetween(value1,value2) 添加字段值在value1和value2之间条件
criteria.andNotBetween(value1,value2) 添加字段值不在value1和value2之间条件

四、应用举例

1.查询

① selectByPrimaryKey()

User user = XxxMapper.selectByPrimaryKey(100); //相当于select * from user where id = 100

② selectByExample() 和 selectByExampleWithBLOGs()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
criteria.andUsernameIsNull();
example.setOrderByClause("username asc,email desc");
List<?>list = XxxMapper.selectByExample(example);
//相当于:select * from user where username = 'wyw' and  username is null order by username asc,email desc

注:在iBator逆向工程生成的文件XxxExample.java中包含一个static的内部类Criteria,Criteria中的方法是定义SQL 语句where后的查询条件。

2.插入数据

①insert()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("admin");
user.setPassword("admin")
user.setEmail("[email protected]");
XxxMapper.insert(user);
//相当于:insert into user(ID,username,password,email) values ('dsfgsdfgdsfgds','admin','admin','[email protected]');

3.更新数据

①updateByPrimaryKey()

User user =new User();
user.setId("dsfgsdfgdsfgds");
user.setUsername("wyw");
user.setPassword("wyw");
user.setEmail("[email protected]");
XxxMapper.updateByPrimaryKey(user);
//相当于:update user set username='wyw', password='wyw', email='[email protected]' where id='dsfgsdfgdsfgds'

②updateByPrimaryKeySelective()

User user = new User();
user.setId("dsfgsdfgdsfgds");
user.setPassword("wyw");
XxxMapper.updateByPrimaryKey(user);
//相当于:update user set password='wyw' where id='dsfgsdfgdsfgds'

③ updateByExample() 和 updateByExampleSelective()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
User user = new User();
user.setPassword("wyw");
XxxMapper.updateByPrimaryKeySelective(user,example);
//相当于:update user set password='wyw' where username='admin'

updateByExample()更新所有的字段,包括字段为null的也更新,建议使用 updateByExampleSelective()更新想更新的字段

4.删除数据

①deleteByPrimaryKey()

XxxMapper.deleteByPrimaryKey(1);  //相当于:delete from user where id=1

②deleteByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
XxxMapper.deleteByExample(example);
//相当于:delete from user where username='admin'

5.查询数据数量

①countByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
int count = XxxMapper.countByExample(example);
//相当于:select count(*) from user where username='wyw'

6.where条件查询或多条件查询

     example.setOrderByClause("age asc");//升序
     example.setDistinct(false);//不去重
 
     if(!StringUtils.isNotBlank(user.getName())){
          Criteria.andNameEqualTo(user.getName());
     }
 
     if(!StringUtils.isNotBlank(user.getSex())){
          Criteria.andSexEqualTo(user.getSex());
     }
 
     List<User> userList=userMapper.selectByExample(example);

类似于:select * from user where name={#user.name} and sex={#user.sex} order by age asc;

     UserExample.Criteria criteria1 = example.createCriteria();
     UserExample.Criteria criteria2 = example.createCriteria();
 
     if(!StringUtils.isNotBlank(user.getName())){
          Criteria1.andNameEqualTo(user.getName());
     }
 
     if(!StringUtils.isNotBlank(user.getSex())){
          Criteria2.andSexEqualTo(user.getSex());
     }
 
     Example.or(criteria2);
     List<User> userList=userMapper.selectByExample(example);

类似于:select * from user where name={#user.name} or sex={#user.sex} ;

7.模糊查询

      if(!StringUtils.isNotBlank(user.getName())){
           criteria.andNameLIke(‘%’+name+’%’);
      }
 
      List<User>  userList=userMapper.selectByExample(example);

类似于:select * from user where name like %{#user.name}%

8.分页查询

        int start = (currentPage - 1) * rows;
        //分页查询中的一页数量
        example.setPageSize(rows);   
        //开始查询的位置
        example.setStartRow(start);
        List<User> userList=userMapper.selectByExample(example);

类似于:select * from user limit start to rows

总结

  1. example用来放一些去重,排序,分类,分页等信息
  2. criteria用来传字段参数
  3. 没有连表操作!!!这也算是他的一个功能不足的情况

参考文章:
https://blog.csdn.net/luluyo/article/details/81708833
https://blog.csdn.net/biandous/article/details/65630783
https://www.cnblogs.com/vickylinj/p/9486098.html

发布了107 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/belongtocode/article/details/103369461