javax.persistence.Query and javax.persistence.EntityManager are both interfaces published by JAP and API s for object persistence.
The EntityManager interface is used to interact with the persistence context. An EntityManager instance is related to the persistence context. A persistence context is a set of entity instances in which the identity of any persistent entity has a unique entity instance. In the context of persistence, entity instances and their lifecycle management. The EntityManager API is used to create and delete persistent entity instances, find entities according to the primary key, and query entities. Entities can be set through a given management. EntityManager instances are defined by a storage unit. All classes defined by a storage unit are related or set by application groups, and must be placed in their mapping to a database.
Common usage of Query interface:
- getResultList(): execute the SELECT query and return the query result as a typeless list.
- getSingleResult(): executes a SELECT query that returns a single untyped result.
- getFirstResult(): the query object is set to the location of the first result retrieved. Returns 0 if setFirstResult is not applied to the query object.
- executeUpdate(): executes an update or delete statement.
- getMaxResults(): set the query object to the maximum number of results retrieved. Return Integer.MAX_VALUEifsetMaxResults is not applied to the query object.
- setFirstResult (int startPosition): sets the position of the first result to be retrieved.
- setMaxResults (int maxResult): sets the maximum number of results to retrieve.
- setParameter (int position, Object value): bind the parameter to the position parameter.
- setParameter: binds the parameter to the named parameter.
Common usage of EntityManager interface:
- persist(): add entity Bean
- flush(): flush the entity changes to the database immediately
- merge (): it's troublesome. It's good to use it. It works well with flush
- Remove(): deletes an object
- createQuery(): returns a Query object to execute JPQL statements
- createNativeQuery(): returns a Query object to execute SQL statements
- refresh(): refresh the entity Bean to get the new object
- contains(): check whether the entity is currently under management
- clear() separates all entities currently being managed
For more usage of Query and EntityManager, please refer to the api documentation: https://www.objectdb.com/api/java/jpa/Query,https://www.objectdb.com/api/java/jpa/EntityManager
The use method is as follows:
package com.yonyou.occ.cr.service; import com.yonyou.occ.cr.entity.ActivityCreditRecordSum; import com.yonyou.occ.cr.entity.CreditLimit; import com.yonyou.occ.cr.entity.CreditLimitExt; import com.yonyou.occ.cr.service.dto.CreditCtrlStrategyDto; import com.yonyou.occ.cr.service.dto.CreditLimitDto; import com.yonyou.occ.cr.service.dto.CreditLimitExtDto; import com.yonyou.ocm.common.annos.IndustryExt; import com.yonyou.ocm.common.datapermission.DataPermissionApi; import com.yonyou.ocm.common.exception.BusinessException; import com.yonyou.ocm.common.utils.CommonUtils; import com.yonyou.ocm.common.web.rest.util.HeaderUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import javax.annotation.Generated; import javax.persistence.EntityManager; import javax.persistence.Query; import java.net.URLDecoder; import java.util.*; /** * For the credit balance service extension class, the logo of promotional activities is added, so the source code needs to be copied and adjusted accordingly */ @Service @IndustryExt @Generated(value = "com.yonyou.ocm.util.codegenerator.CodeGenerator") public class CreditBalanceExtService extends CreditBalanceService{ @Autowired private ActivityCreditRecordService activityCreditRecordService; @Autowired private EntityManager entityManager; @Autowired private DataPermissionApi dataPermissionApi; @Autowired private CreditCtrlStrategyService strategyService; @Autowired private JpaProperties jpaProperties; /** * Add promotion activity dimension to credit query modify source * @param: * @param creditLimitDtoList * @param recalculation * @param prefixKey * @return: */ @Override public List<CreditLimitDto> queryLimit(List<CreditLimitDto> creditLimitDtoList, Boolean recalculation, String prefixKey) { if(CollectionUtils.isEmpty(creditLimitDtoList)){ return null; } return queryLimitByActivity(creditLimitDtoList,recalculation,prefixKey); } /** * Here, directly copy the source code of CreditBalanceService.queryLimit to modify modify the modify source */ public List<CreditLimitDto> queryLimitByActivity(List<CreditLimitDto> creditLimitDtoList, Boolean recalculation, String prefixKey) { if(CollectionUtils.isEmpty(creditLimitDtoList)){ return null; } Set<String> creditCtrlStrategyId = new HashSet<>(); Set<String> customerId = new HashSet<>(); Set<String> productLineId = new HashSet<>(); Set<String> currencyId = new HashSet<>(); Set<String> creditCtrlStrategyIdWithProductLineId = new HashSet<>(); Set<String> customerIdWithProductLineId = new HashSet<>(); Set<String> currencyIdWithProductLineId = new HashSet<>(); Set<String> activityId = new HashSet<>(); for (CreditLimitDto creditLimitDto : creditLimitDtoList) { Boolean withProductLine = false; if (StringUtils.isNotBlank(creditLimitDto.getProductGroupId())) { productLineId.add(creditLimitDto.getProductGroupId()); withProductLine = true; } CreditLimitExtDto creditLimitExtDto = (CreditLimitExtDto)creditLimitDto; if(StringUtils.isNotBlank(creditLimitExtDto.getActivity())){ activityId.add(creditLimitExtDto.getActivity()); } if (withProductLine) { if (StringUtils.isNotBlank(creditLimitDto.getCreditCtrlStrategyId())) { creditCtrlStrategyIdWithProductLineId.add(creditLimitDto.getCreditCtrlStrategyId()); } if (StringUtils.isNotBlank(creditLimitDto.getCustomerId())) { customerIdWithProductLineId.add(creditLimitDto.getCustomerId()); } if (StringUtils.isNotBlank(creditLimitDto.getCurrencyId())) { currencyIdWithProductLineId.add(creditLimitDto.getCurrencyId()); } }else { if (StringUtils.isNotBlank(creditLimitDto.getCreditCtrlStrategyId())) { creditCtrlStrategyId.add(creditLimitDto.getCreditCtrlStrategyId()); } if (StringUtils.isNotBlank(creditLimitDto.getCustomerId())) { customerId.add(creditLimitDto.getCustomerId()); } if (StringUtils.isNotBlank(creditLimitDto.getCurrencyId())) { currencyId.add(creditLimitDto.getCurrencyId()); } } } List<ActivityCreditRecordSum> actCreditRecordSumList = new ArrayList<>(); if(recalculation){ if (StringUtils.isBlank(prefixKey)) { throw new BusinessException("Query recalculation result. The unique ID of this query cannot be empty"); } if(CollectionUtils.isNotEmpty(creditCtrlStrategyId)&& CollectionUtils.isNotEmpty(customerId)&& CollectionUtils.isNotEmpty(currencyId)){ if (customerId.size() > 1000) { String[] customerIdArray = customerId.toArray(new String[customerId.size()]); int beginIndex = 0; boolean continueflag = true; do { Set<String> tempCustomerIds = new HashSet<>(); if (customerIdArray.length > (beginIndex + 1000)) { tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,beginIndex+1000))); }else{ tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,customerIdArray.length))); continueflag = false; } if (CollectionUtils.isNotEmpty(activityId)) { actCreditRecordSumList.addAll(activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyId,tempCustomerIds,currencyId,activityId,prefixKey)); }else{ actCreditRecordSumList.addAll(activityCreditRecordService.querySumNoActivityWithRecalculationCreditRecord(creditCtrlStrategyId,customerId,currencyId,prefixKey)); } beginIndex += 1000; } while (continueflag); }else{ if (CollectionUtils.isNotEmpty(activityId)) { actCreditRecordSumList.addAll(activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyId,customerId,currencyId,activityId,prefixKey)); }else{ actCreditRecordSumList.addAll(activityCreditRecordService.querySumNoActivityWithRecalculationCreditRecord(creditCtrlStrategyId,customerId,currencyId,prefixKey)); } } } if(CollectionUtils.isNotEmpty(creditCtrlStrategyIdWithProductLineId)&& CollectionUtils.isNotEmpty(customerIdWithProductLineId)&& CollectionUtils.isNotEmpty(productLineId)&& CollectionUtils.isNotEmpty(currencyIdWithProductLineId)){ //List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = new ArrayList<>(); if (customerIdWithProductLineId.size() > 1000) { String[] customerIdArray = customerIdWithProductLineId.toArray(new String[customerIdWithProductLineId.size()]); int beginIndex = 0; boolean continueflag = true; do { Set<String> tempCustomerIds = new HashSet<>(); if (customerIdArray.length > (beginIndex + 1000)) { tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,beginIndex+1000))); }else{ tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,customerIdArray.length))); continueflag = false; } List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = null; if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyIdWithProductLineId,tempCustomerIds,productLineId,currencyIdWithProductLineId,activityId,prefixKey); }else{ creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyIdWithProductLineId, tempCustomerIds, productLineId, currencyIdWithProductLineId, prefixKey); } if (CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)) { actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } beginIndex += 1000; } while (continueflag); }else{ List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = null; if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyIdWithProductLineId,customerIdWithProductLineId,productLineId,currencyIdWithProductLineId,activityId,prefixKey); }else{ creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithRecalculationCreditRecord(creditCtrlStrategyIdWithProductLineId, customerIdWithProductLineId, productLineId, currencyIdWithProductLineId, prefixKey); } if (CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)) { actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } } // if(CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)){ // actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); // } } }else{ if(CollectionUtils.isNotEmpty(creditCtrlStrategyId)&& CollectionUtils.isNotEmpty(customerId)&& CollectionUtils.isNotEmpty(currencyId) ){ if (customerId.size() > 1000) { String[] customerIdArray = customerId.toArray(new String[customerId.size()]); int beginIndex = 0; boolean continueflag = true; do { Set<String> tempCustomerIds = new HashSet<>(); if (customerIdArray.length > (beginIndex + 1000)) { tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,beginIndex+1000))); }else{ tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,customerIdArray.length))); continueflag = false; } List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = null; if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithCreditRecord(creditCtrlStrategyId,tempCustomerIds,currencyId,activityId); }else { creditRecordSumListWithProductLine = activityCreditRecordService.querySumNoActivityWithCreditRecord(creditCtrlStrategyId,tempCustomerIds,currencyId); } if (CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)) { actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } beginIndex += 1000; } while (continueflag); }else{ List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = null; if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithCreditRecord(creditCtrlStrategyId,customerId,currencyId,activityId); }else { creditRecordSumListWithProductLine = activityCreditRecordService.querySumNoActivityWithCreditRecord(creditCtrlStrategyId,customerId,currencyId); } if (CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)) { actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } } } if(CollectionUtils.isNotEmpty(creditCtrlStrategyIdWithProductLineId)&& CollectionUtils.isNotEmpty(customerIdWithProductLineId)&& CollectionUtils.isNotEmpty(productLineId)&& CollectionUtils.isNotEmpty(currencyIdWithProductLineId) ){ if (customerIdWithProductLineId.size() > 1000) { String[] customerIdArray = customerIdWithProductLineId.toArray(new String[customerIdWithProductLineId.size()]); int beginIndex = 0; boolean continueflag = true; do { Set<String> tempCustomerIds = new HashSet<>(); if (customerIdArray.length > (beginIndex + 1000)) { tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,beginIndex+1000))); }else{ tempCustomerIds.addAll(Arrays.asList(ArrayUtils.subarray(customerIdArray,beginIndex,customerIdArray.length))); continueflag = false; } List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = new ArrayList<>(); if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithCreditRecord(creditCtrlStrategyIdWithProductLineId,tempCustomerIds,productLineId,currencyIdWithProductLineId,activityId); }else { creditRecordSumListWithProductLine = activityCreditRecordService.querySumNoActivityWithCreditRecord(creditCtrlStrategyIdWithProductLineId,tempCustomerIds,productLineId,currencyIdWithProductLineId); } if(CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)){ actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } beginIndex += 1000; } while (continueflag); }else{ List<ActivityCreditRecordSum> creditRecordSumListWithProductLine = new ArrayList<>(); if (CollectionUtils.isNotEmpty(activityId)) { creditRecordSumListWithProductLine = activityCreditRecordService.querySumByActivityOrNullWithCreditRecord(creditCtrlStrategyIdWithProductLineId,customerIdWithProductLineId,productLineId,currencyIdWithProductLineId,activityId); }else { creditRecordSumListWithProductLine = activityCreditRecordService.querySumNoActivityWithCreditRecord(creditCtrlStrategyIdWithProductLineId,customerIdWithProductLineId,productLineId,currencyIdWithProductLineId); } if(CollectionUtils.isNotEmpty(creditRecordSumListWithProductLine)){ actCreditRecordSumList.addAll(creditRecordSumListWithProductLine); } } } } //Assign the queried value to the displayed Dto copyValuesInToResult(creditLimitDtoList,actCreditRecordSumList); return creditLimitDtoList; } /** * Here, directly copy the source code of CreditBalanceService.copyValuesInToResult to modify the modify source */ //Assign the corresponding credit balance, pre occupied amount, collection amount and occupied amount to the queried credit limit table private void copyValuesInToResult(List<CreditLimitDto> creditLimitDtoList, List<ActivityCreditRecordSum> creditRecordSumList) { if(!CollectionUtils.isEmpty(creditRecordSumList)){ for(CreditLimitDto creditLimitDto:creditLimitDtoList){ // Add category of promotional activities CreditLimitExtDto creditLimitExtDto = (CreditLimitExtDto)creditLimitDto; String limitActivity = creditLimitExtDto.getActivity()==null?"":creditLimitExtDto.getActivity(); for(ActivityCreditRecordSum creditRecordSum:creditRecordSumList){ String sumActivity = creditRecordSum.getActivity()==null?"":creditRecordSum.getActivity(); if(creditLimitDto.getCreditCtrlStrategyId().equals(creditRecordSum.getCreditCtrlStrategyId())&& creditLimitDto.getCustomerId().equals(creditRecordSum.getCustomerId())&& (StringUtils.isBlank(creditLimitDto.getProductGroupId())|| StringUtils.isNotBlank(creditLimitDto.getProductGroupId())&&StringUtils.isNotBlank(creditRecordSum.getProductLineId())&&creditLimitDto.getProductGroupId().equals(creditRecordSum.getProductLineId()))&& creditLimitDto.getCurrencyId().equals(creditRecordSum.getCurrencyId())&& limitActivity.equals(sumActivity)){ creditLimitDto.setOccupyLimit(creditRecordSum.getReceivableAmount().subtract(creditRecordSum.getReceiptAmount()).add(creditRecordSum.getOccupyLimit()).subtract(creditRecordSum.getAccountDeductionAmount())); creditLimitDto.setPreoccupyLimit(creditRecordSum.getReceivableAmount().subtract(creditRecordSum.getReceiptAmount()).add(creditRecordSum.getPreoccupyLimit()).subtract(creditRecordSum.getAccountDeductionAmount())); creditLimitDto.setOrderOccupyLimit(creditRecordSum.getOccupyLimit()); creditLimitDto.setOrderPreoccupyLimit(creditRecordSum.getPreoccupyLimit()); creditLimitDto.setOccupyBalance(creditLimitDto.getCreditLimit().subtract(creditLimitDto.getOccupyLimit())); creditLimitDto.setPreoccupyBalance(creditLimitDto.getCreditLimit().subtract(creditLimitDto.getPreoccupyLimit())); creditLimitDto.setReceiptAmount(creditRecordSum.getReceiptAmount()); creditLimitDto.setReceivableAmount(creditRecordSum.getReceivableAmount()); creditLimitDto.setAccountDeductionAmount(creditRecordSum.getAccountDeductionAmount()); break; } creditLimitDto.setOccupyBalance(creditLimitDto.getCreditLimit()); creditLimitDto.setPreoccupyBalance(creditLimitDto.getCreditLimit()); } } }else{ for(CreditLimitDto creditLimitDto:creditLimitDtoList){ creditLimitDto.setPreoccupyBalance(creditLimitDto.getCreditLimit()); creditLimitDto.setOccupyBalance(creditLimitDto.getCreditLimit()); } } } /** * Here, directly copy the source code of CreditBalanceService.findAllWithComputer to modify it */ @Override public Page<CreditLimitDto> findAllWithComputer(Map<String, Object> searchParams, Pageable pageable, boolean recalculation) { // By default, it is arranged in reverse order of creation time if (pageable.getSort() == null) { pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), getDefaultSort()); } //Common parameters List<CreditLimit> entityList = null; int count = 0; Map<String, Object> params = new HashMap<>(); StringBuilder jpql = new StringBuilder(); StringBuilder jpqlCount = new StringBuilder(); //If it is an Oracle database, execute the following query; otherwise, execute the MySQL query if ("ORACLE".equalsIgnoreCase(jpaProperties.getDatabase().name())) { StringBuilder whereClause = new StringBuilder(); StringBuilder sql = new StringBuilder(); whereClause.append(" where rn <= 1 and c.dr=0 "); //Add logo of promotion sql.append("select * from (select lim.*,limext.ACTIVITY_ID, " + // "row_number() over(partition by lim.customer_id,lim.pk_org,lim.sale_org_id,lim.product_line_id " + "row_number() over(partition by lim.customer_id,lim.credit_ctrl_strategy_id,lim.product_line_id,limext.ACTIVITY_ID " + "order by lim.start_date desc,lim.end_date asc) rn " + "from cr_credit_limit lim,cr_credit_limit_ext limext where lim.id=limext.id and lim.start_date <= :sysdate " + "and lim.end_date >= :sysdate and lim.dr=0 ) c "); jpql.append(sql); jpqlCount.append(sql); int flag = 0; if (searchParams.containsKey("EQ_creditCtrlStrategy.id")|| searchParams.containsKey("EQ_creditCtrlStrategy.organization") || searchParams.containsKey("EQ_creditCtrlStrategy.saleOrg") || searchParams.containsKey("EQ_customer") || searchParams.containsKey("IN_customer") || searchParams.containsKey("EQ_productGroup")) { flag = 1; jpql.append(" join cr_credit_ctrl_strategy str on c.credit_ctrl_strategy_id = str.id "); //organization jpqlCount.append(" join cr_credit_ctrl_strategy str on c.credit_ctrl_strategy_id = str.id "); if (searchParams.containsKey("EQ_creditCtrlStrategy.id")) { String creditCtrlStrategyId = (String) searchParams.get("EQ_creditCtrlStrategy.id"); whereClause.append(" and str.id =:creditCtrlStrategyId"); params.put("creditCtrlStrategyId", creditCtrlStrategyId); } if (searchParams.containsKey("EQ_creditCtrlStrategy.organization")) { String organization = (String) searchParams.get("EQ_creditCtrlStrategy.organization"); whereClause.append(" and str.pk_org =:organization"); params.put("organization", organization); } if (searchParams.containsKey("EQ_creditCtrlStrategy.saleOrg")) { //Sales organization String saleOrg = (String) searchParams.get("EQ_creditCtrlStrategy.saleOrg"); whereClause.append(" and str.sale_org_id =:saleOrg"); params.put("saleOrg", saleOrg); } if (searchParams.containsKey("EQ_customer")) { //customer String customer = (String) searchParams.get("EQ_customer"); whereClause.append(" and c.customer_id =:customer"); params.put("customer", customer); } // At 14:45:22 on May 10, 2019, no data can be found according to the customer's query if (searchParams.containsKey("IN_customer")) { //customer String customerIdstr = (String) searchParams.get("IN_customer"); whereClause.append(" and c.CUSTOMER_ID in(:customerIds)"); params.put("customerIds", Arrays.asList(customerIdstr.split(","))); } if (searchParams.containsKey("EQ_productGroup")) { //Product line String productGroup = (String) searchParams.get("EQ_productGroup"); whereClause.append(" and c.product_line_id =:productGroup"); params.put("productGroup", productGroup); } } //Add query criteria for promotional activities if (searchParams.containsKey("IN_activity")) { String activityIdstr = (String) searchParams.get("IN_activity"); whereClause.append(" and c.ACTIVITY_ID in(:activityIds)"); params.put("activityIds", Arrays.asList(activityIdstr.split(","))); } //Add query criteria for promotional activities //If there are parameters with promotion activities, the data permission will not be verified if (!searchParams.containsKey("IN_activity")) { //Splicing Data permission filtering conditions String userId = CommonUtils.getCurrentUserId(); ResponseEntity<Map<String, Set<String>>> orgAuthParams = dataPermissionApi.getAuthParamByApp("creditoccupy", userId); if (HeaderUtil.hasError(orgAuthParams)) { logger.error(URLDecoder.decode(orgAuthParams.getHeaders().get("X-OCC-message").get(0))); } else { Map<String, Set<String>> orgAuthParamsData = orgAuthParams.getBody(); if (flag == 0 && orgAuthParams.getBody().size() != 0) { jpql.append(" join cr_credit_ctrl_strategy str on c.credit_ctrl_strategy_id = str.id "); jpqlCount.append(" join cr_credit_ctrl_strategy str on c.credit_ctrl_strategy_id = str.id "); } if (orgAuthParamsData.containsKey("creditCtrlStrategy.organization")) { whereClause.append(" and str.pk_org in :orgAuth"); params.put("orgAuth", orgAuthParamsData.get("creditCtrlStrategy.organization")); } if (orgAuthParamsData.containsKey("creditCtrlStrategy.saleOrg")) { whereClause.append(" and str.sale_org_id in :saleOrgAuth"); params.put("saleOrgAuth", orgAuthParamsData.get("creditCtrlStrategy.saleOrg")); } if (orgAuthParamsData.containsKey("customer")) { whereClause.append(" and c.customer_id in :customerAuth"); params.put("customerAuth", orgAuthParamsData.get("customer")); } } } params.put("sysdate", new Date()); jpql.append(whereClause); jpqlCount.append(whereClause); } //Execute query Query query = entityManager.createNativeQuery(jpql.toString(), CreditLimitExt.class); Query queryCount = entityManager.createNativeQuery(jpqlCount.toString(), CreditLimitExt.class); //Set paging query parameters query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize()); query.setMaxResults(pageable.getPageSize()); this.setParameters(query, params); this.setParameters(queryCount, params); entityList = query.getResultList(); count = queryCount.getResultList().size(); if (CollectionUtils.isEmpty(entityList)) { return new PageImpl<>(new ArrayList<>(0), pageable, count); } Set<String> ids = new HashSet<>(); for (int i = 0; i < entityList.size(); i++) { ids.add(entityList.get(i).getCreditCtrlStrategy().getId()); } List<CreditCtrlStrategyDto> strategyList = strategyService.findByIdIn(ids.toArray(new String[0])); if (strategyList == null || strategyList.size() <= 0) { throw new BusinessException("No corresponding credit control policy found"); } List<CreditLimitDto> dtoList = this.entitiesToDtos(entityList); //Encapsulate map split double loop Map<String, CreditCtrlStrategyDto> map = new HashMap<>(); for (CreditCtrlStrategyDto ctrlStrategyDto : strategyList) { map.put(ctrlStrategyDto.getId(), ctrlStrategyDto); } CreditCtrlStrategyDto dto = new CreditCtrlStrategyDto(); for (int i = 0; i < dtoList.size(); i++) { dto = map.get(dtoList.get(i).getCreditCtrlStrategyId()); if (dto != null) { dtoList.get(i).setOrganizationId(dto.getOrganizationId()); dtoList.get(i).setOrganizationCode(dto.getOrganizationCode()); dtoList.get(i).setOrganizationName(dto.getOrganizationName()); dtoList.get(i).setSaleOrgId(dto.getSaleOrgId()); dtoList.get(i).setSaleOrgCode(dto.getSaleOrgCode()); dtoList.get(i).setSaleOrgName(dto.getSaleOrgName()); } } dtoList = queryLimit(dtoList, recalculation, (String) searchParams.get("EQ_prefixKey")); Page<CreditLimitDto> page = new PageImpl<>(dtoList, pageable, count); return page; } /** * Here, directly copy the source code of CreditBalanceService.setParameters to modify modify the modify source */ private void setParameters(Query query, Map<String,Object> params){ for(Map.Entry<String,Object> entry:params.entrySet()){ query.setParameter(entry.getKey(),entry.getValue()); } } /** * Query the credit information within the credit validity range according to the parameters, and only query the first 1000 data * @param: * @param customerId Customer primary key * @param activityIds Promotion activity PK * @return: key=Promotion activity pK value = credit entity */ public Map<String, CreditLimitExtDto> findCreditBalance(String customerId, String[] activityIds) { Assert.notNull(customerId, "Query credit customer PK cannot be blank"); if (ArrayUtils.isEmpty(activityIds)) { throw new BusinessException("Query credit activity PK cannot be empty"); } if (activityIds.length > 50) { throw new BusinessException("The number of credit activities queried cannot exceed 50"); } //Only 1000 queries Pageable pageable = new PageRequest(0, 1000); Map<String, Object> searchParams = new HashMap<>(); //Customer primary key condition searchParams.put("IN_customer", customerId); //Active primary key condition searchParams.put("IN_activity", StringUtils.join(activityIds,",")); Page<CreditLimitDto> results = super.findAll(searchParams, pageable); List<CreditLimitDto> creditLimitDtos = results.getContent(); Map<String, CreditLimitExtDto> creditLimitMap = new HashMap<>(); if (CollectionUtils.isEmpty(creditLimitDtos)) { return creditLimitMap; } for (CreditLimitDto creditLimitDto : creditLimitDtos) { CreditLimitExtDto creditLimitExtDto = (CreditLimitExtDto)creditLimitDto; String activity = creditLimitExtDto.getActivity(); if (StringUtils.isNotBlank(activity)) { if (creditLimitMap.containsKey(activity)) { throw new BusinessException("Existing customer["+creditLimitExtDto.getCustomerName()+"]+Activities["+ creditLimitExtDto.getActivityName()+"]Multiple credit limits within the validity period, please check"); } creditLimitMap.put(activity,creditLimitExtDto); } } return creditLimitMap; } }