Mybatis Plus爲咱們提供了以下的一些條件構造器,咱們能夠利用它們實現查詢條件、刪除條件、更新條件的構造。html
條件構造器用於給以下的Mapper方法傳參,一般狀況下:vue
public interface BaseMapper<T> extends Mapper<T> { int delete(@Param("ew") Wrapper<T> wrapper); int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper); T selectOne(@Param("ew") Wrapper<T> queryWrapper); Integer selectCount(@Param("ew") Wrapper<T> queryWrapper); List<T> selectList(@Param("ew") Wrapper<T> queryWrapper); List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper); List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper); IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper); IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper); }
String name = "字母"; //name不爲空 String email = ""; //email爲空串 QueryWrapper<User> query = new QueryWrapper<>(); query.like(StringUtils.isNotEmpty(name), "name", name) //由於email爲空串,該條件未生效 .like(StringUtils.isNotEmpty(email), "email", email); List<User> list = userMapper.selectList(query); list.forEach(System.out::println);
email=「」
,因此.like(StringUtils.isNotEmpty(email), "email", email);
的條件不成立。SELECT id,name,age,email,create_time FROM user WHERE name LIKE %字母%
//構造條件 QueryWrapper<User> query = new QueryWrapper<>(); Map<String, Object> params = new HashMap<>(); params.put("name", "字母哥"); params.put("age", 18); params.put("email", null); // query.allEq(params,false); query.allEq((k, v) -> !k.equals("name"), params, false); List<User> list = userMapper.selectList(query); list.forEach(System.out::println);
params.put("name", "字母哥");
這個查詢條件被過濾掉params.put("email", null);
這個查詢條件被過濾掉最終執行的SQL以下:spring
SELECT id,name,age,email,create_time FROM user WHERE age = ?
請參考:官方文檔:條件構造器後端
// LambdaQueryWrapper<User> lambdaQ = new QueryWrapper<User>().lambda(); // LambdaQueryWrapper<User> lambdaQ = new LambdaQueryWrapper<>(); LambdaQueryWrapper<User> lambdaQ = Wrappers.lambdaQuery(); lambdaQ.like(User::getName, "字母") .lt(User::getAge, 18); List<User> list = userMapper.selectList(lambdaQ);
lambda條件構造器,最終執行SQL以下:springboot
SELECT id,name,age,email,create_time FROM user WHERE name LIKE %字母% AND age < 18
List<User> list = new LambdaQueryChainWrapper<User>(userMapper) .likeRight(User::getName, "字母") .and(q -> q.lt(User::getAge, 40) .or() .isNotNull(User::getEmail) ) .list(); list.forEach(System.out::println);
lambda條件構造器,最終執行SQL以下:mybatis
SELECT id,name,age,email,create_time FROM user WHERE name LIKE '字母%' AND ( age < 18 OR email IS NOT NULL )
以爲對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創做動力! 。另外,筆者最近一段時間輸出了以下的精品內容,期待您的關注。app