原代码:
@Override
public PageResult<AddressBookResDTO> pageList(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
Long userId = UserContext.currentUserId();
//使用工具类转为分页前的page
Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
//IService的分页函数
Page<AddressBook> page = page(addressBookPage,lambdaQuery().eq(AddressBook::getUserId, userId));
return PageUtils.toPage(page,AddressBookResDTO.class);
}
这段代码看似很正常
但执行后会报异常
异常为:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 'ew != null and ew.sqlFirst != null'. Cause: org.apache.ibatis.ognl.OgnlException: sqlFirst [com.baomidou.mybatisplus.core.exceptions.MybatisPlusException: can not use this method for "getSqlFirst"]
出错原因:
代码中直接使用了IService的lambdaQuery()的返回参数做page函数的第二个入参,虽说编译通过,但是在执行时且出现了问题
解决办法:
1)如果还要使用IService的lambdaQuery(),则需要加getWrapper()
@Override
public PageResult<AddressBookResDTO> pageList(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
Long userId = UserContext.currentUserId();
//使用工具类转为分页前的page
Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
//IService的分页函数
Page<AddressBook> page = page(addressBookPage,lambdaQuery().getWrapper().eq(AddressBook::getUserId, userId));
return PageUtils.toPage(page,AddressBookResDTO.class);
}
2)使用原始的QueryWrapper
@Override
public PageResult<AddressBookResDTO> pageList(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
Long userId = UserContext.currentUserId();
//使用工具类转为分页前的page
Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
//IService的分页函数
// Page<AddressBook> page = page(addressBookPage,lambdaQuery().getWrapper().eq(AddressBook::getUserId, userId));
Page<AddressBook> page = page(addressBookPage, new QueryWrapper<AddressBook>().eq("user_id", userId));
return PageUtils.toPage(page,AddressBookResDTO.class);
}
3)当然QueryWrapper要手动写属性,写错了就不好了,可以手动创建LambdaQueryWrapper
@Override
public PageResult<AddressBookResDTO> pageList(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
Long userId = UserContext.currentUserId();
//使用工具类转为分页前的page
Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
//IService的分页函数
// Page<AddressBook> page = page(addressBookPage,lambdaQuery().getWrapper().eq(AddressBook::getUserId, userId));
// Page<AddressBook> page = page(addressBookPage, new QueryWrapper<AddressBook>().eq("user_id", userId));
Page<AddressBook> page = page(addressBookPage, new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId,userId));
return PageUtils.toPage(page,AddressBookResDTO.class);
}
提示:
直接调用IService的lambdaQuery()虽说代码简洁,但是出现的问题要注意!