Search code examples
javaselectejbpersistenceentitymanager

Passing EntityManager between EJB classes?


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?


Solution

  • Best practice is to inject the entityManager in any EJB that needs it.

    @PersistenceContext
    private EntityManager entityManager;
    

    The container will search for persistence.xml file, and inject the entity manager in your EJB.

    You can specify different persistence units, with unitName:

    @PersistenceContext(unitName = "unitName")
    private EntityManager entityManager;
    

    The scope of the entity manager is tied to the transaction, so every EJB participating of the same transaction will be injected with the same entityManager.