@ApplicationScoped CDI bean and @PersistenceContext - is this safe?

前端 未结 2 1345
Happy的楠姐
Happy的楠姐 2021-02-01 03:48

Is it safe to do something like this with CDI?

@Named
@ApplicationScoped
public class DAO {

   @PersistenceContext
   private EntityManager entityManager;

}
         


        
2条回答
  •  攒了一身酷
    2021-02-01 04:48

    What about this approach:

    
        @RequestScoped
        class EntityManagerProducer {
        
            @PersistenceContext
            private EntityManager entityManager;
        
            @Produces
            @RequestScoped
            public EntityManager produceEntityManager() {
              return this.entityManager;
            }
        }
    
    

    And in CDI Beans of any scope:

    
    @Inject
    private EntityManager entityManager;
    
    

    The entity manager should be created in every single request, creating a new entity manager when it passes one CDI bean which it injects. In the injected CDI Bean, you get one entity manager which is used within the request. If a transaction is needed, the entity manager will join it. So you get a new entity manager in every request which means, everything is cleaned up at the end and you cannot get thread conflicts. Simple and easy, isn't it?

提交回复
热议问题