一、MybatisPlusListObjs概述
MybatisPlus是一款優秀的ORM框架,可以幫我們快速開發資料庫相關的應用程序。MybatisPlusListObjs是MybatisPlus的一個核心API,它可以用來進行查詢操作。在這裡,我們將對MybatisPlusListObjs進行詳細的闡述。
二、MybatisPlusListObjs基本使用
MybatisPlus提供了豐富的查詢API,包括ListObjs、ListMaps、ListEntitys等。其中,ListObjs是最常用的API之一,用於返回指定條件下的記錄數。
public List
上面的API中,第一個方法返回所有數據,第二個方法返回指定條件下的數據,第三個和第四個方法可以將返回對象進行轉換。
例如:
public List findDictList() {
List dictList = dictMapper.selectList(null);
DictTypeEnum.codeOf(dictList.get(0).getType());
return dictList;
}
上面的代碼演示了如何使用MybatisPlusListObjs查詢所有數據。
三、MybatisPlusListObjs詳解
1.使用Wrapper條件查詢
Wrapper是MyBatis-Plus提供的一個查詢條件構造器。通過wrapper可以構造查詢時使用的條件。以下是一個例子:
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("status", CommonConstant.STATUS_NORMAL);
queryWrapper.eq("type", type);
queryWrapper.orderByAsc("sort");
List dictList = dictMapper.selectList(queryWrapper);
上面的代碼展示了如何使用QueryWrapper進行條件查詢,並按sort欄位升序排列。
2.返回自定義對象列表
除了默認情況下返回Object類型,MybatisPlus還支持返回自定義對象列表。以下是一個例子:
public List findDictList(DictQueryDto dictQueryDto) {
QueryWrapper queryWrapper = new QueryWrapper();
......
List dictList = dictMapper.selectList(queryWrapper).stream().map(dict -> ConvertUtil.convert(dict, DictDto.class))
.collect(Collectors.toList());
return dictList;
}
上面的代碼展示了如何將Dict對象轉換成DictDto對象並返回。
四、MybatisPlusListObjs高級使用
1.分頁查詢
MybatisPlus提供了非常便利的分頁查詢方式,只需要傳入當前頁和每頁顯示的記錄數即可,以下是一個例子:
public IPage findDictPage(Page page, DictQueryDto dictQueryDto) {
QueryWrapper queryWrapper = new QueryWrapper();
......
return dictMapper.selectPage(page, queryWrapper);
}
上面的代碼演示了如何使用selectPage方法進行分頁查詢。
2.關聯查詢
在實際項目中,我們經常需要進行關聯查詢。MybatisPlus也提供了方便的關聯查詢方式,以下是一個例子:
public List findProjectList(ProjectQueryDto projectQueryDto) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.like(StringUtils.isNotEmpty(projectQueryDto.getProjectName()), "project_name", projectQueryDto.getProjectName());
queryWrapper.eq("status", CommonConstant.STATUS_NORMAL);
queryWrapper.orderByAsc("sort");
return projectMapper.selectList(queryWrapper).stream().map(project -> {
ProjectDto projectDto = ConvertUtil.convert(project, ProjectDto.class);
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("project_id", project.getId());
projectDto.setProjectWorkplaceList(projectWorkplaceMapper.selectList(wrapper));
return projectDto;
}).collect(Collectors.toList());
}
上面的代碼演示了如何進行多表關聯查詢。
3.批量操作
MybatisPlus強大的批量操作功能也值得我們好好學習和使用。以下是一個例子:
public void batchSave(List dictList) {
dictList.forEach(dict -> dictMapper.insert(dict));
}
上面的代碼展示了MybatisPlus批量插入數據的方式。
五、總結
在實際項目開發中,MybatisPlusListObjs是一個非常常用的API,能夠幫助我們快速完成數據查詢操作。除了基本使用方法外,還有一些高級功能也值得我們去探索和使用。同時,我們也需要認真閱讀MybatisPlus官方文檔,以便更好地理解和應用。
原創文章,作者:UXRGS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370917.html
微信掃一掃
支付寶掃一掃