日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot封装统一查询对象进行多条件查询案例(mybatis和mybatis-plus+反射两种版本)

發布時間:2024/9/30 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot封装统一查询对象进行多条件查询案例(mybatis和mybatis-plus+反射两种版本) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • mybatis版本:
    • 通用查詢接口
    • 封裝輔助查詢類:
    • 通用controller:
    • 自定義注解
    • controller service mapper測試
  • mybatis-plus實現版本
    • entity
    • 自定義注解
    • 自定義輔助查詢類(利用反射)
    • controller
    • service

界面:

mybatis版本:

通用查詢接口

  • 功能:1、單條查詢 2、分頁+搜索 3、查詢數量
public interface ICommonQuery {/*** 根據id查詢明細。** @param id 資源id* @return 資源*/Object selectOne(Long id) throws Exception;/*** 自定義查詢** @param parameterMap 查詢參數* @return 查詢結果*/List<?> select(Map<String, String> parameterMap) throws Exception;/*** 查詢數量** @param parameterMap 查詢參數* @return 查詢結果*/Long counts(Map<String, String> parameterMap) throws Exception;/*** 新增數據** @param obj* @return*/int insert(JSONObject obj, HttpServletRequest request) throws Exception;/*** 更新數據** @param obj* @return*/int update(JSONObject obj, HttpServletRequest request) throws Exception;/*** 刪除數據** @param id* @return*/int delete(Long id, HttpServletRequest request) throws Exception;/*** 批量刪除數據** @param ids* @return*/int deleteBatch(String ids, HttpServletRequest request) throws Exception;/*** 查詢名稱是否存在** @param id* @return*/int checkIsNameExist(Long id, String name) throws Exception; }

封裝輔助查詢類:

@Service public class CommonQueryManager {@Resourceprivate InterfaceContainer container;/*** 查詢單條** @param apiName 接口名稱* @param id ID*/public Object selectOne(String apiName, Long id) throws Exception {if (StringUtil.isNotEmpty(apiName) && id!=null) {return container.getCommonQuery(apiName).selectOne(id);}return null;}/*** 查詢* @param apiName* @param parameterMap* @return*/public List<?> select(String apiName, Map<String, String> parameterMap)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).select(parameterMap);}return new ArrayList<Object>();}/*** 計數* @param apiName* @param parameterMap* @return*/public Long counts(String apiName, Map<String, String> parameterMap)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).counts(parameterMap);}return BusinessConstants.DEFAULT_LIST_NULL_NUMBER;}/*** 插入* @param apiName* @param obj* @return*/@Transactional(value = "transactionManager", rollbackFor = Exception.class)public int insert(String apiName, JSONObject obj, HttpServletRequest request) throws Exception{if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).insert(obj, request);}return 0;}/*** 更新* @param apiName* @param obj* @return*/@Transactional(value = "transactionManager", rollbackFor = Exception.class)public int update(String apiName, JSONObject obj, HttpServletRequest request)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).update(obj, request);}return 0;}/*** 刪除* @param apiName* @param id* @return*/@Transactional(value = "transactionManager", rollbackFor = Exception.class)public int delete(String apiName, Long id, HttpServletRequest request)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).delete(id, request);}return 0;}/*** 批量刪除* @param apiName* @param ids* @return*/@Transactional(value = "transactionManager", rollbackFor = Exception.class)public int deleteBatch(String apiName, String ids, HttpServletRequest request)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).deleteBatch(ids, request);}return 0;}/*** 判斷是否存在* @param apiName* @param id* @param name* @return*/public int checkIsNameExist(String apiName, Long id, String name) throws Exception{if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).checkIsNameExist(id, name);}return 0;}}

CommonQueryManager中的成員變量InterfaceContainer類:

@Service public class InterfaceContainer {private final Map<String, ICommonQuery> configComponentMap = new HashMap<>();@Autowired(required = false)private synchronized void init(ICommonQuery[] configComponents) {for (ICommonQuery configComponent : configComponents) {ResourceInfo info = AnnotationUtils.getAnnotation(configComponent, ResourceInfo.class);if (info != null) {configComponentMap.put(info.value(), configComponent);}}}public ICommonQuery getCommonQuery(String apiName) {return configComponentMap.get(apiName);} }

通過

public List<?> select(String apiName, Map<String, String> parameterMap)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).select(parameterMap);}return new ArrayList<Object>(); }

來對不同接口進行分別查詢
通過

public Long counts(String apiName, Map<String, String> parameterMap)throws Exception {if (StringUtil.isNotEmpty(apiName)) {return container.getCommonQuery(apiName).counts(parameterMap);}return BusinessConstants.DEFAULT_LIST_NULL_NUMBER;}

來對某一個接口進行條件查詢,其中parameterMap是自己傳入的參數:
驗證:
在上面的方法中加上

parameterMap.entrySet().forEach(e->{log.info(e.getKey()+":"+e.getValue());});

搜索框輸入:


控制臺:

輸入:

控制臺:

通用controller:

@RestController public class ResourceController {@Resourceprivate CommonQueryManager configResourceManager;@GetMapping(value = "/{apiName}/info")public String getList(@PathVariable("apiName") String apiName,@RequestParam("id") Long id,HttpServletRequest request) throws Exception {Object obj = configResourceManager.selectOne(apiName, id);Map<String, Object> objectMap = new HashMap<String, Object>();if(obj != null) {objectMap.put("info", obj);return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else {return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);}}@GetMapping(value = "/{apiName}/list")public String getList(@PathVariable("apiName") String apiName,@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,@RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,@RequestParam(value = Constants.SEARCH, required = false) String search,HttpServletRequest request)throws Exception {Map<String, String> parameterMap = ParamUtils.requestToMap(request);parameterMap.put(Constants.SEARCH, search);Map<String, Object> objectMap = new HashMap<String, Object>();if (pageSize != null && pageSize <= 0) {pageSize = 10;}String offset = ParamUtils.getPageOffset(currentPage, pageSize);if (StringUtil.isNotEmpty(offset)) {parameterMap.put(Constants.OFFSET, offset);}List<?> list = configResourceManager.select(apiName, parameterMap);if (list != null) {System.out.println("訪問接口:"+apiName);objectMap.put("total", configResourceManager.counts(apiName, parameterMap));objectMap.put("rows", list);return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else {objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);objectMap.put("rows", new ArrayList<Object>());return returnJson(objectMap, "查找不到數據", ErpInfo.OK.code);}}@PostMapping(value = "/{apiName}/add", produces = {"application/javascript", "application/json"})public String addResource(@PathVariable("apiName") String apiName,@RequestBody JSONObject obj, HttpServletRequest request)throws Exception {Map<String, Object> objectMap = new HashMap<String, Object>();int insert = configResourceManager.insert(apiName, obj, request);if(insert > 0) {return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else if(insert == -1) {return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);} else {return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);}}@PutMapping(value = "/{apiName}/update", produces = {"application/javascript", "application/json"})public String updateResource(@PathVariable("apiName") String apiName,@RequestBody JSONObject obj, HttpServletRequest request)throws Exception {Map<String, Object> objectMap = new HashMap<String, Object>();int update = configResourceManager.update(apiName, obj, request);if(update > 0) {return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else if(update == -1) {return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);} else {return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);}}@DeleteMapping(value = "/{apiName}/delete", produces = {"application/javascript", "application/json"})public String deleteResource(@PathVariable("apiName") String apiName,@RequestParam("id") Long id, HttpServletRequest request)throws Exception {Map<String, Object> objectMap = new HashMap<String, Object>();int delete = configResourceManager.delete(apiName, id, request);if(delete > 0) {return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else if(delete == -1) {return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);} else {return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);}}@DeleteMapping(value = "/{apiName}/deleteBatch", produces = {"application/javascript", "application/json"})public String batchDeleteResource(@PathVariable("apiName") String apiName,@RequestParam("ids") String ids, HttpServletRequest request)throws Exception {Map<String, Object> objectMap = new HashMap<String, Object>();int delete = configResourceManager.deleteBatch(apiName, ids, request);if(delete > 0) {return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);} else if(delete == -1) {return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);} else {return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);}}@GetMapping(value = "/{apiName}/checkIsNameExist")public String checkIsNameExist(@PathVariable("apiName") String apiName,@RequestParam Long id, @RequestParam(value ="name", required = false) String name,HttpServletRequest request)throws Exception {Map<String, Object> objectMap = new HashMap<String, Object>();int exist = configResourceManager.checkIsNameExist(apiName, id, name);if(exist > 0) {objectMap.put("status", true);} else {objectMap.put("status", false);}return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);}}

自定義注解

表示可以用于條件查詢的字段

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface ResourceInfo {String value(); }

controller service mapper測試

下面以賬單為例:
對一個entity寫兩個類一個自定義注解:

AccountHeadComponent 拓展ICommonQuery接口:

@Service(value = "accountHead_component") @AccountHeadResource public class AccountHeadComponent implements ICommonQuery {//其他方法忽略private List<?> getAccountHeadList(Map<String, String> map)throws Exception {String search = map.get(Constants.SEARCH);String type = StringUtil.getInfo(search, "type");String roleType = StringUtil.getInfo(search, "roleType");String billNo = StringUtil.getInfo(search, "billNo");String beginTime = StringUtil.getInfo(search, "beginTime");String endTime = StringUtil.getInfo(search, "endTime");Long organId = StringUtil.parseStrLong(StringUtil.getInfo(search, "organId"));Long creator = StringUtil.parseStrLong(StringUtil.getInfo(search, "creator"));Long handsPersonId = StringUtil.parseStrLong(StringUtil.getInfo(search, "handsPersonId"));return accountHeadService.select(type, roleType, billNo, beginTime, endTime, organId, creator, handsPersonId, QueryUtils.offset(map), QueryUtils.rows(map));}}} @GetMapping(value = "/getStatistics")public BaseResponseInfo getStatistics(@RequestParam("name") String name,@RequestParam("serialNo") String serialNo,HttpServletRequest request) throws Exception {BaseResponseInfo res = new BaseResponseInfo();try {Map<String, Object> map = accountService.getStatistics(name, serialNo);res.code = 200;res.data = map;} catch(Exception e){e.printStackTrace();res.code = 500;res.data = "獲取數據失敗";}return res;}

service:

@Service public class AccountHeadService {private Logger logger = LoggerFactory.getLogger(AccountHeadService.class);@Resourceprivate AccountHeadMapper accountHeadMapper;@Resourceprivate AccountHeadMapperEx accountHeadMapperEx;@Resourceprivate OrgaUserRelService orgaUserRelService;@Resourceprivate AccountItemService accountItemService;@Resourceprivate SupplierService supplierService;@Resourceprivate LogService logService;@Resourceprivate AccountItemMapperEx accountItemMapperEx;//對應 CommonQueryManager的 public List<?> select(String apiName, Map<String, String> parameterMap)throws Exception { // if (StringUtil.isNotEmpty(apiName)) { // return container.getCommonQuery(apiName).select(parameterMap); // } // return new ArrayList<Object>(); // }public List<AccountHeadVo4ListEx> select(String type, String roleType, String billNo, String beginTime, String endTime,Long organId, Long creator, Long handsPersonId, int offset, int rows) throws Exception{List<AccountHeadVo4ListEx> resList = new ArrayList<>();try{String [] creatorArray = getCreatorArray(roleType);beginTime = Tools.parseDayToTime(beginTime,BusinessConstants.DAY_FIRST_TIME);endTime = Tools.parseDayToTime(endTime,BusinessConstants.DAY_LAST_TIME);List<AccountHeadVo4ListEx> list = accountHeadMapperEx.selectByConditionAccountHead(type, creatorArray, billNo, beginTime, endTime, organId, creator, handsPersonId, offset, rows);if (null != list) {for (AccountHeadVo4ListEx ah : list) {if(ah.getChangeAmount() != null) {ah.setChangeAmount(ah.getChangeAmount().abs());}if(ah.getTotalPrice() != null) {ah.setTotalPrice(ah.getTotalPrice().abs());}if(ah.getBillTime() !=null) {ah.setBillTimeStr(getCenternTime(ah.getBillTime()));}resList.add(ah);}}}catch(Exception e){JshException.readFail(logger, e);}return resList;} //忽略其他增刪改的方法

mapper:

public interface AccountHeadMapperEx {List<AccountHeadVo4ListEx> selectByConditionAccountHead(@Param("type") String type,@Param("creatorArray") String[] creatorArray,@Param("billNo") String billNo,@Param("beginTime") String beginTime,@Param("endTime") String endTime,@Param("organId") Long organId,@Param("creator") Long creator,@Param("handsPersonId") Long handsPersonId,@Param("offset") Integer offset,@Param("rows") Integer rows);//省略其他方法}

連接另外的幾個表取出需要查詢的字段進行條件查詢:

<select id="selectByConditionAccountHead" parameterType="com.jsh.erp.datasource.entities.AccountHeadExample" resultMap="ResultMapEx">select ah.*, s.supplier OrganName, p.Name HandsPersonName, u.username userName, a.Name AccountNamefrom jsh_account_head ahleft join jsh_supplier s on ah.organ_id=s.id and ifnull(s.delete_Flag,'0') !='1'left join jsh_user u on ah.creator=u.id and ifnull(u.Status,'0') ='0'left join jsh_person p on ah.hands_person_id=p.id and ifnull(p.delete_Flag,'0') !='1'left join jsh_account a on ah.account_id=a.id and ifnull(a.delete_Flag,'0') !='1'where 1=1<if test="billNo != null"><bind name="bindBillNo" value="'%'+billNo+'%'"/>and ah.bill_no like #{bindBillNo}</if><if test="type != null">and ah.type=#{type}</if><if test="beginTime != null">and ah.bill_time &gt;= #{beginTime}</if><if test="endTime != null">and ah.bill_time &lt;= #{endTime}</if><if test="organId != null">and ah.organ_id=#{organId}</if><if test="handsPersonId != null">and ah.hands_person_id=#{handsPersonId}</if><if test="creator != null">and ah.creator=#{creator}</if><if test="creatorArray != null">and ah.creator in (<foreach collection="creatorArray" item="creator" separator=",">#{creator}</foreach>)</if>and ifnull(ah.delete_flag,'0') !='1'order by ah.id desc<if test="offset != null and rows != null">limit #{offset},#{rows}</if></select>

當點擊不同的選項時執行不同的sql:
Execute SQL:SELECT COUNT(id) FROM jsh_account_head WHERE jsh_account_head.tenant_id = 63 AND 1 = 1 AND type = ‘付款’ AND ifnull(delete_flag, ‘0’) != ‘1’

Execute SQL:SELECT COUNT(id) FROM jsh_account_head WHERE jsh_account_head.tenant_id = 63 AND 1 = 1 AND type = ‘轉賬’ AND ifnull(delete_flag, ‘0’) != ‘1’

mybatis-plus實現版本

entity

對每一個entity都定義一個查詢類:

@Data public class DeptDto implements Serializable {/** ID */private Long id;/** 名稱 */private String name;/** 上級部門 */private Long pid;/** 狀態 */private Boolean enabled;private List<DeptDto> children;/** 創建日期 */private Timestamp createTime;public String getLabel() {return name;} } @Data public class DeptQueryCriteria {@Query(type = Query.Type.IN, propName = "id")private Set<Long> ids;@Query(type = Query.Type.INNER_LIKE)private String name;@Queryprivate Boolean enabled;@Queryprivate Long pid;@Query(type = Query.Type.BETWEEN)private List<Timestamp> createTime; }

自定義注解

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Query {// Dong ZhaoYang 2017/8/7 基本對象的屬性名String propName() default "";// Dong ZhaoYang 2017/8/7 查詢方式Type type() default Type.EQUAL;/*** 多字段模糊搜索,僅支持String類型字段,多個用逗號隔開, 如@Query(blurry = "email,username")*/String blurry() default "";enum Type {// jie 2019/6/4 相等EQUAL// Dong ZhaoYang 2017/8/7 大于等于, GREATER_THAN// Dong ZhaoYang 2017/8/7 小于等于, LESS_THAN// Dong ZhaoYang 2017/8/7 中模糊查詢, INNER_LIKE// Dong ZhaoYang 2017/8/7 左模糊查詢, LEFT_LIKE// Dong ZhaoYang 2017/8/7 右模糊查詢, RIGHT_LIKE// Dong ZhaoYang 2017/8/7 小于, LESS_THAN_NQ// jie 2019/6/4 包含, IN// 不等于, NOT_EQUAL// between, BETWEEN// 不為空, NOT_NULL// 查詢時間, UNIX_TIMESTAMP}}

自定義輔助查詢類(利用反射)

package co.yixiang.common.utils;import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import co.yixiang.annotation.Query; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.extern.slf4j.Slf4j;import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List;/*** @author Zheng Jie* @date 2019-6-4 14:59:48*/ @Slf4j @SuppressWarnings({"unchecked", "all"}) public class QueryHelpPlus {public static <R, Q> QueryWrapper getPredicate(R obj, Q query) {QueryWrapper<R> queryWrapper = new QueryWrapper<R>();if (query == null) {return queryWrapper;}try {List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());for (Field field : fields) {boolean accessible = field.isAccessible();field.setAccessible(true);Query q = field.getAnnotation(Query.class);if (q != null) {String propName = q.propName();String blurry = q.blurry();String attributeName = isBlank(propName) ? field.getName() : propName;attributeName = humpToUnderline(attributeName);Class<?> fieldType = field.getType();Object val = field.get(query);if (ObjectUtil.isNull(val) || "".equals(val)) {continue;}// 模糊多字段if (ObjectUtil.isNotEmpty(blurry)) {String[] blurrys = blurry.split(",");//queryWrapper.or();queryWrapper.and(wrapper -> {for (int i = 0; i < blurrys.length; i++) {String column = humpToUnderline(blurrys[i]);//if(i!=0){wrapper.or();//}wrapper.like(column, val.toString());}});continue;}String finalAttributeName = attributeName;switch (q.type()) {case EQUAL://queryWrapper.and(wrapper -> wrapper.eq(finalAttributeName, val));queryWrapper.eq(attributeName, val);break;case GREATER_THAN:queryWrapper.ge(finalAttributeName, val);break;case LESS_THAN:queryWrapper.le(finalAttributeName, val);break;case LESS_THAN_NQ:queryWrapper.lt(finalAttributeName, val);break;case INNER_LIKE:queryWrapper.like(finalAttributeName, val);break;case LEFT_LIKE:queryWrapper.likeLeft(finalAttributeName, val);break;case RIGHT_LIKE:queryWrapper.likeRight(finalAttributeName, val);break;case IN:if (CollUtil.isNotEmpty((Collection<Long>) val)) {queryWrapper.in(finalAttributeName, (Collection<Long>) val);}break;case NOT_EQUAL:queryWrapper.ne(finalAttributeName, val);break;case NOT_NULL:queryWrapper.isNotNull(finalAttributeName);break;case BETWEEN:List<Object> between = new ArrayList<>((List<Object>) val);queryWrapper.between(finalAttributeName, between.get(0), between.get(1));break;case UNIX_TIMESTAMP:List<Object> UNIX_TIMESTAMP = new ArrayList<>((List<Object>) val);if (!UNIX_TIMESTAMP.isEmpty()) {SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");long time1 = fm.parse(UNIX_TIMESTAMP.get(0).toString()).getTime() / 1000;long time2 = fm.parse(UNIX_TIMESTAMP.get(1).toString()).getTime() / 1000;queryWrapper.between(finalAttributeName, time1, time2);}break;default:break;}}field.setAccessible(accessible);}} catch (Exception e) {log.error(e.getMessage(), e);}return queryWrapper;}private static boolean isBlank(final CharSequence cs) {int strLen;if (cs == null || (strLen = cs.length()) == 0) {return true;}for (int i = 0; i < strLen; i++) {if (!Character.isWhitespace(cs.charAt(i))) {return false;}}return true;}private static List<Field> getAllFields(Class clazz, List<Field> fields) {if (clazz != null) {fields.addAll(Arrays.asList(clazz.getDeclaredFields()));getAllFields(clazz.getSuperclass(), fields);}return fields;}/**** 駝峰命名轉為下劃線命名** @param para* 駝峰命名的字符串*/public static String humpToUnderline(String para) {StringBuilder sb = new StringBuilder(para);int temp = 0;//定位if (!para.contains("_")) {for (int i = 0; i < para.length(); i++) {if (Character.isUpperCase(para.charAt(i))) {sb.insert(i + temp, "_");temp += 1;}}}return sb.toString();} }

controller

@Log("查詢部門")@ApiOperation("查詢部門")@GetMapping("/dept")public ResponseEntity<Object> getDepts(DeptQueryCriteria criteria) {// 數據權限criteria.setIds(dataScope.getDeptIds());List<DeptDto> deptDtos = generator.convert(deptService.queryAll(criteria), DeptDto.class);return new ResponseEntity<>(deptService.buildTree(deptDtos), HttpStatus.OK);}

service

List<Dept> queryAll(DeptQueryCriteria criteria); @Service @AllArgsConstructor //@CacheConfig(cacheNames = "dept") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, Dept> implements DeptService {@Overridepublic List<Dept> queryAll(DeptQueryCriteria criteria) {return baseMapper.selectList(QueryHelpPlus.getPredicate(Dept.class, criteria));}/*** 構建樹形數據** @param deptDtos 原始數據* @return /*/@Overridepublic Object buildTree(List<DeptDto> deptDtos) {Set<DeptDto> trees = new LinkedHashSet<>();Set<DeptDto> depts = new LinkedHashSet<>();List<String> deptNames = deptDtos.stream().map(DeptDto::getName).collect(Collectors.toList());boolean isChild;DeptQueryCriteria criteria = new DeptQueryCriteria();List<Dept> deptList = this.queryAll(criteria);for (DeptDto deptDto : deptDtos) {isChild = false;if ("0".equals(deptDto.getPid().toString())) {trees.add(deptDto);}for (DeptDto it : deptDtos) {if (it.getPid().equals(deptDto.getId())) {isChild = true;if (deptDto.getChildren() == null) {deptDto.setChildren(new ArrayList<>());}deptDto.getChildren().add(it);}}if (isChild) {depts.add(deptDto);for (Dept dept : deptList) {if (dept.getId().equals(deptDto.getPid()) && !deptNames.contains(dept.getName())) {depts.add(deptDto);}}}}if (CollectionUtils.isEmpty(trees)) {trees = depts;}Integer totalElements = deptDtos.size();Map<String, Object> map = new HashMap<>(2);map.put("totalElements", totalElements);map.put("content", CollectionUtils.isEmpty(trees) ? deptDtos : trees);return map;}//省略其他方法 }

總結

以上是生活随笔為你收集整理的springboot封装统一查询对象进行多条件查询案例(mybatis和mybatis-plus+反射两种版本)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。