龙哥网

龙哥网

Mybatis Example的高级用法详解_java
2022-02-28

目录
  • Mybatis Example的高级用法

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

    • 二. example实例方法

    • 三. 使用案例

  • 说说Mybatis Example常见用法

    • 一. 说明

    • 二. 排序查询

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


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;
    }
免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。