Skip to content

Commit

Permalink
#813 - change in approach for executing search query
Browse files Browse the repository at this point in the history
  • Loading branch information
petmongrels committed Nov 8, 2024
1 parent 599768e commit 1393294
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ public long getCount(EncounterSearchRequest searchRequest) {
query.getParameters().forEach((name, value) -> {
sql.setParameter(name, value);
});
BigInteger count = (BigInteger) sql.getSingleResult();
return count.longValue();
return (Long) sql.getSingleResult();
} finally {
setRoleBackToUser();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
package org.avni.server.dao;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import jakarta.transaction.Transactional;
import org.avni.server.dao.search.SearchBuilder;
import org.avni.server.dao.search.SqlQuery;
import org.avni.server.domain.SubjectType;
import org.avni.server.web.request.webapp.search.SubjectSearchRequest;
import org.hibernate.query.sql.internal.NativeQueryImpl;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import jakarta.persistence.EntityManager;

import jakarta.persistence.*;

import jakarta.persistence.Query;
import jakarta.transaction.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

Expand All @@ -35,24 +31,6 @@ public SubjectSearchRepository(EntityManager entityManager, SubjectTypeRepositor
this.subjectTypeRepository = subjectTypeRepository;
}

private List<Map<String, Object>> convertTuplesToMap(List<?> tuples) {
List<Map<String, Object>> result = new ArrayList<>();

tuples.forEach(object -> {
if (object instanceof Tuple single) {
Map<String, Object> tempMap = new HashMap<>();
for (TupleElement<?> key : single.getElements()) {
tempMap.put(key.getAlias(), single.get(key));
}
result.add(tempMap);
} else {
throw new RuntimeException("Query should return instance of Tuple");
}
});

return result;
}

@Transactional
public List<Map<String, Object>> search(SubjectSearchRequest searchRequest, SearchBuilder searchBuilder) {
SubjectType subjectType = StringUtils.isEmpty(searchRequest.getSubjectType()) ? null : subjectTypeRepository.findByUuid(searchRequest.getSubjectType());
Expand All @@ -62,18 +40,19 @@ public List<Map<String, Object>> search(SubjectSearchRequest searchRequest, Sear
logger.debug("Executing query: " + query.getSql());
logger.debug("Parameters: " + query.getParameters());
Query sql = entityManager.createNativeQuery(query.getSql());
NativeQueryImpl nativeQuery = (NativeQueryImpl) sql;
nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
query.getParameters().forEach((name, value) -> {
sql.setParameter(name, value);
});
List resultList = sql.getResultList();
return convertTuplesToMap(resultList);
return sql.getResultList();
} finally {
setRoleBackToUser();
}
}

@Transactional
public BigInteger getTotalCount(SubjectSearchRequest searchRequest, SearchBuilder searchBuilder) {
public Long getTotalCount(SubjectSearchRequest searchRequest, SearchBuilder searchBuilder) {
SubjectType subjectType = StringUtils.isEmpty(searchRequest.getSubjectType()) ? null : subjectTypeRepository.findByUuid(searchRequest.getSubjectType());
SqlQuery query = searchBuilder.getSQLCountQuery(searchRequest, subjectType);
try {
Expand All @@ -83,7 +62,7 @@ public BigInteger getTotalCount(SubjectSearchRequest searchRequest, SearchBuilde
sql.setParameter(name, value);
});

return (BigInteger) sql.getSingleResult();
return (Long) sql.getSingleResult();
} finally {
setRoleBackToUser();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

Expand All @@ -31,18 +33,18 @@ public LinkedHashMap<String, Object> search(SubjectSearchRequest subjectSearchRe
logger.info("Searching for individuals");
List<Map<String, Object>> searchResults = subjectSearchRepository.search(subjectSearchRequest, new SubjectSearchQueryBuilder());
logger.info("Found " + searchResults.size() + " individuals");
BigInteger totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectSearchQueryBuilder());
Long totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectSearchQueryBuilder());
logger.info("Total count of individuals: " + totalCount);
return constructIndividual(searchResults, totalCount);
}

private LinkedHashMap<String, Object> constructIndividual(List<Map<String, Object>> individualList, BigInteger totalCount) {
LinkedHashMap<String, Object> recordsMap = new LinkedHashMap<String, Object>();
private LinkedHashMap<String, Object> constructIndividual(List<Map<String, Object>> individualList, Long totalCount) {
LinkedHashMap<String, Object> recordsMap = new LinkedHashMap<>();
List<Long> individualIds = individualList.stream()
.map(individualRecord -> Long.valueOf((Integer) individualRecord.get("id")))
.collect(Collectors.toList());
List<Long> addressIds = individualList.stream()
.map(individualRecord -> ((BigInteger) individualRecord.get("addressId")).longValue())
.map(individualRecord -> (Long) individualRecord.get("addressId"))
.collect(Collectors.toList());

List<SearchSubjectEnrolledProgram> searchSubjectEnrolledPrograms = !individualIds.isEmpty() ?
Expand All @@ -58,7 +60,7 @@ private LinkedHashMap<String, Object> constructIndividual(List<Map<String, Objec
.filter(x -> x.getId().equals(individualId))
.map(SearchSubjectEnrolledProgram::getProgram)
.collect(Collectors.toList()));
individualRecord.put("addressLevel", titleLineages.get(((BigInteger) individualRecord.get("addressId")).longValue()));
individualRecord.put("addressLevel", titleLineages.get((Long) individualRecord.get("addressId")));
}).collect(Collectors.toList());
recordsMap.put("totalElements", totalCount);
recordsMap.put("listOfRecords", listOfRecords);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
import org.springframework.stereotype.Service;

import jakarta.transaction.Transactional;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -106,7 +104,7 @@ public LinkedHashMap<String, Object> searchSubjects(SubjectSearchRequest subject
List<Long> subjectIds = searchResults.stream().map(s -> Long.parseLong(s.get("id").toString())).collect(Collectors.toList());
List<UserSubjectAssignment> userSubjectAssignmentBySubjectIds = userSubjectAssignmentRepository.findUserSubjectAssignmentBySubject_IdIn(subjectIds);
List<Long> addressIds = searchResults.stream()
.map(searchResult -> ((BigInteger) searchResult.get("addressId")).longValue())
.map(searchResult -> (Long) searchResult.get("addressId"))
.collect(Collectors.toList());
Map<Long, String> titleLineages = addressLevelService.getTitleLineages(addressIds);
Map<String, List<User>> groupedSubjects = userSubjectAssignmentBySubjectIds.stream()
Expand All @@ -122,10 +120,10 @@ public LinkedHashMap<String, Object> searchSubjects(SubjectSearchRequest subject
.orElseGet(Stream::empty)
.map(uw -> pf.createProjection(UserWebProjection.class, uw)).collect(Collectors.toList());
searchResult.put("assignedUsers", userWebProjections);
searchResult.put("addressLevel", titleLineages.get(((BigInteger) searchResult.get("addressId")).longValue()));
searchResult.put("addressLevel", titleLineages.get((Long) searchResult.get("addressId")));
}

BigInteger totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder());
Long totalCount = subjectSearchRepository.getTotalCount(subjectSearchRequest, new SubjectAssignmentSearchQueryBuilder());

LinkedHashMap<String, Object> recordsMap = new LinkedHashMap<>();
recordsMap.put("totalElements", totalCount);
Expand Down

0 comments on commit 1393294

Please sign in to comment.