Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/65936860/passing-entitymanager-between-ejb-classes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
88 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...