I have the following code in a Java EJB
class that makes a call to another service class and passes an entityManager
as a parameter:
AppointmentService EJB:
try {
entityManager = entityManagement.createEntityManager(client);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Appointment> query = builder.createQuery(Appointment.class);
Root<Appointment> from = query.from(Appointment.class);
CriteriaQuery<Appointment> selectQuery = query.select(from);
searchService.searchByKeywords(searchRequest, searchResults, entityManager, selectQuery, keywordPredicates);
} catch (Exception e) {
}
SearchService EJB:
public List<Appointment> searchByKeywords(AppointmentSearchRequest searchRequest, List<Appointment> searchResults, EntityManager entityManager, CriteriaQuery<Appointment> selectQuery, Optional<List<Predicate>> keywordPredicates) {
Map<Integer, Appointment> uniqueSearchResults = new HashMap<>();
if(keywordPredicates.isPresent()){
for (Predicate singlePredicate : keywordPredicates.get()) {
selectQuery = selectQuery.where(singlePredicate);
List<Appointment> singleQueryResults = entityManager.createQuery(selectQuery).setFirstResult(searchRequest.getIndex()).setMaxResults(searchRequest.getSize()).getResultList();
searchResults.addAll(singleQueryResults);
}
}
return searchResults;
}
Is it best practice to pass entityManager
, selectQuery
between EJB classes, or should I be instantiating the entityManager in the SearchService EJB
?