MyBatis的Example类详解

Example类的定义?

第一次幕课网教程看到关于这方面教时,没有懂example起什么用,感觉不用example也可以查询了,后来认真一看才知道这是查询条件生成器

 

 


mybatis-generator会为每个字段产生Criterion,为底层的mapper.xml创建动态sql。如果表的字段比较多,产生的example类会十分庞大。理论上通过example类可以构造你想到的任何筛选条件。在mybatis-generator中加以配置,配置数据表的生成操作就可以自动生成example了。
mybatis 的mapper接⼝提供了增、删、改、查的⽅法。避免过多使⽤xml来直接写sql。

 

 

 

核心方法,通过mapper . 弹出方法名

 

Example类指定如何构建一个动态的where子句. 表中的每个non-BLOB列可以被包括在where子句中. 例子是展示此类用法的最好方式.

Example类可以用来生成一个几乎无限的where子句.

Example类包含一个内部静态类 Criteria 包含一个用 anded 组合在where子句中的条件列表. Example类包含一个 List 属性,所有内部类Criteria中的子句会用 ored组合在一起. 使用不同属性的 Criteria 类允许您生成无限类型的where子句.

创建 Criteria 对象 可以使用Example类中的 createCriteria() 或者 or() . 如果 Criteria 对象是用 createCriteria() 创建的,它会自动为 List 属性添加一个 Criteria 对象 - 这使得它更容易写一个简单的where子句, 如果您不需要 or 或者其他几个子句组合的话. 用 or(Criteria criteria) 方法创建 Criteria 对象, 方法里的 criteria 对象会被添加进 Criteria 对象的列表中.

重要 我们推荐您只使用 or() 方法创建 Criteria 对象. 我们相信这种方法使代码更有可读性

 

Mybatis Example 用法手册,接口方法和实例方法

近几个项目一直使用的mybatis来对数据库做查询,期间用到了很多高效简洁的查询方法,特此记录和分享。

 

一. mapper接口中的函数及方法,

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

 

二. example实例方法

example 用于添加条件,相当于where后面的部分,理论上单表的任何复杂条件查询都可以使用example来完成。

方法说明
example.setOrderByClause(“字段名 ASC”); 添加升序排列条件,DESC为降序
example.setDistinct(false) 去除重复,boolean型,true为选择不重复的记录。
example.and(Criteria criteria) 为example添加criteria查询条件,关系为与
example.or(Criteria criteria) 为example添加criteria查询条件,关系为或
criteria.andXxxIsNull 添加字段xxx为null的条件
criteria.andXxxIsNotNull 添加字段xxx不为null的条件
criteria.andXxxEqualTo(value) 添加xxx字段等于value条件
criteria.andXxxNotEqualTo(value) 添加xxx字段不等于value条件
criteria.andXxxGreaterThan(value) 添加xxx字段大于value条件
criteria.andXxxGreaterThanOrEqualTo(value) 添加xxx字段大于等于value条件
criteria.andXxxLessThan(value) 添加xxx字段小于value条件
criteria.andXxxLessThanOrEqualTo(value) 添加xxx字段小于等于value条件
criteria.andXxxIn(List<?>) 添加xxx字段值在List<?>条件
criteria.andXxxNotIn(List<?>) 添加xxx字段值不在List<?>条件
criteria.andXxxLike(“%”+value+”%”) 添加xxx字段值为value的模糊查询条件
criteria.andXxxNotLike(“%”+value+”%”) 添加xxx字段值不为value的模糊查询条件
criteria.andXxxBetween(value1,value2) 添加xxx字段值在value1和value2之间条件
criteria.andXxxNotBetween(value1,value2) 添加xxx字段值不在value1和value2之间条件

 

三. 使用案例

1.基本字段查询

      // 1.使用criteria
      Example example = new Example(User.class);
            Criteria criteria = example.createCriteria();
            criteria.andEqualTo("name", name);
            criteria.andNotEqualTo("id", id);
            criteria.andEqualTo("userId", uid);
            List<User> list = userMapper.selectByExample(example);
            
            // 不使用criteria,实则example.and()本质底层还是返回的criteria,倒是可以简便写法。
            Example example = new Example(User.class);
   example.and()
                .andEqualTo("name", name)
                .andEqualTo("id", id)
                .andEqualTo("userId", uid);
    List<User> list = userMapper.selectByExample(example);
  等效于:select * from user where name = #{name} and id = #{id} and uid = #{uid}

2. and or 查询

  Example example = new Example(User.getClass());
        // where 条件
        Criteria criteria = example.createCriteria();
        Criteria criteria1 = example.createCriteria();
        
        criteria.andIn("id", ids);
        criteria1.orLike("des", "%" + des + "%");
        criteria1.orLike("name", "%" + name + "%");
        example.and(criteria1);
        example.and().andEqualTo("status", staus)
 等效于:where id in ( #{ids} ) and ( name like concat(‘%', #{name} ,'%') or des like concat(‘%', #{des} ,'%') ) and status = #{status} 

注意:如果不加 example.and(criteria1);,则默认example只添加生成的第一个criteria,criteria1 将不会加到此条件中

3. 数组参数的条件查询

public Example test(List<String> names, String sex) {
  Example example = new Example(User.getClass());
  example.and().andEqualTo("sex", sex)
        Example.Criteria criteria = example.createCriteria();
        for (String str : names) {
             criteria.orLike("name", str);
         }
         example.and(criteria);
         List<User> list = userMapper.selectByExample(example);
            
 等效于:where sex = #{sex} and ( name like concat(‘%', #{name1} ,'%') or name like concat(‘%', #{name2} ,'%') )
}

 

说说Mybatis Example常见用法

 

一. 说明

我们在使用mybatis example做业务 增/删/改/查时,会遇到一些场景。做一下记录。

 

二. 排序查询

使用mybatis example方式做查询时候,业务需要按照条件排序,比如:创建时间倒序

example.setOrderByClause("create_time desc");

2.1 示例:

 @Override
    public UpgradeNotifyInfoDTO queryLatestNotify(Integer appType) {
        UpgradeNotifyInfoDTO notifyDTO=new UpgradeNotifyInfoDTO();
        SportAppUpgradeNotifyExample example = new SportAppUpgradeNotifyExample();
        example.setOrderByClause("`create_time` desc");
        SportAppUpgradeNotifyExample.Criteria criteria =  example.createCriteria();
        criteria.andAppTypeEqualTo(appType);
        // 0- 禁用 1-启用
        criteria.andStatusEqualTo(1);
        List<SportAppUpgradeNotify> list = upgradeNotifyMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)){
            BeanUtils.copyProperties(list.get(0),notifyDTO);
        }
        return notifyDTO;
    }

注: 多条件排序写法如下:

   ReservationProductOrderDetailExample example = new ReservationProductOrderDetailExample();
        example.setOrderByClause("`reservate_time` desc,`reservate_start_time` desc, `create_time` desc");
        ReservationProductOrderDetailExample.Criteria criteria = example.createCriteria();

 

三. 查询limit, 只返回前50条数据

3.1 借助PageHelper

我们通过Pagehelper做分页查询,那么limit同样可以使用Pagehelper。如下,查询符合条件中的前50条。这里不会返回数据总数 count

PageHelper.startPage(1, 50);
 public List<ShopCityInfoRespDTO> queryShopList(String shopCityName,String shopCityId) {
        List<ShopCityInfoRespDTO> shopCityList = new ArrayList<>();
        ShopInfoExample example = new ShopInfoExample();
        ShopInfoExample.Criteria criteria =  example.createCriteria();
        criteria.andStatusEqualTo("0");
        if(!StringUtils.isEmpty(shopCityId)) {
            criteria.andShopIdEqualTo(shopCityId);
        }
        if(!StringUtils.isEmpty(shopCityName)) {
            criteria.andShopNameLike("%" + shopCityName + "%");
        }
        // 这里限制查询50条数据,但不能返回总数
        PageHelper.startPage(1, 50);
        List<ShopInfo>  shopInfoList = shopInfoMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(shopInfoList)){
           return shopCityList;
        }
        for (ShopInfo shopInfo : shopInfoList){
            ShopCityInfoRespDTO  respDTO = new ShopCityInfoRespDTO();
            respDTO.setCompanyId(shopInfo.getCompanyId());
            respDTO.setShopCityId(shopInfo.getShopId());
            respDTO.setShopCityName(shopInfo.getShopName());
            respDTO.setShopCityCode(shopInfo.getShopCode());
            respDTO.setShopType(1);
            shopCityList.add(respDTO);
        }
        return shopCityList;
    }

其它示例:均来自别的网站,以作方例实用时参考

 

 

1.按条件统计:

  Example example = new Example(User.class);
  //Criteria criteria = example.createCriteria();
  example.createCriteria().andEqualTo("id", "1001" )
  UserMapper.countByExample(example);
   //等同于:select count(*) from user where id='1001'
2.查询:

(1)主键查询:selectByPrimaryKey

User user = UserMapper.selectByPrimaryKey("1001");

//等同于:select * from user where id = "1001"
(2)条件查询:selectByExample (and条件)

Example example = new Example(User.class);
example.createCriteria().andEqualTo("id", "1001" )
.andEqualTo("name", "小杨");
User user = UserMapper.selectByExample(example);

//等同于:select * from user where id = "1001" and name = '小杨'
selectByExample (or条件)

Example example = new Example(User.class);
example.or.andEqualTo("id", "1001" )
example.or.andEqualTo("name", "小杨");
User user = UserMapper.selectByExample(example);

//等同于:select * from user where id = "1001" or name = '小杨'
selectByExample (and+or多条件查询)

Example example = new Example(User.class);
example.createCriteria().andEqualTo("id", "1001" )
.andEqualTo("name", "小杨");
example.and().orEqualTo("age","18")
.orEqualTo("sex","1");
List<User> user = UserMapper.selectByExample(example);

//等同于:
SELECT id,user_id,user_name,pass_word FROM user WHERE ( id = "1001" and name= "小杨" ) and ( age= "18" or sex= "1" )
3.插入:

User user = new User();
user.setId("1002");
user.setAge("18");
user.setName("小王");
user.setSex("0")
UserMapper.insert(user);
//等同于:
insert into user(id,age,name,sex) values ('1002','18','小王','0');
4.更新:
(1)updateByPrimaryKeyimaryKey 按主键更新(会把没有设置的值设置为空)

User user = new User();
user.setId("1002");
user.setName("小王");
user.setAge("18");
user.setSex("0")
UserMapper.updateByPrimaryKey(user);
//等同于:update user set sex= "0" name='小王', age='18' where id='1002'
(2)updateByExampleSelective 按主键更新(不会把null 更新)

/*注意:updateByExample()更新所有的字段,包括字段为null的,建议使用 updateByExampleSelective()更新需要更新的字段*/

Example example = new Example(User.class);
example.createCriteria().andEqualTo("id","1002");

User user = new User();
user.setName("小王");

UserMapper.updateByExampleSelective(user,example);

//等同于:update user set Name='小王' where id='1002'
5.删除:
(1)deleteByPrimaryKey 按主键删除

UserMapper.deleteByPrimaryKey("1002");
//相当于:delete from user where id="1002"
(2)deleteByExample 按条件删除

Example example = new Example(User.class);
example.createCriteria().andEqualTo("name","小王");
UserMapper.deleteByExample(example);
//等同于:delete from user where name ='小王'

版权声明:本文为CSDN博主「leaf__yang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/leaf__yang/article/details/125273086

posted @ 2022-12-13 08:30  稷下元歌  阅读(4503)  评论(0编辑  收藏  举报