Java – should the entitymanager of JPA be requestscoped?

I am using JBoss 7 to develop web applications based on Java EE 6

class ForumServiceEJB
{
    @PersistenceContext(type=EXTENDED)
    private EntityManager em;

}

class TopicServiceEJB
{
    @PersistenceContext(type=EXTENDED)
    private EntityManager em;

}

When I use the entitymanager of forumserviceejb to update some data and make changes into the DB, but the entitymanager of topicserviceejb cannot see these changes and always gets the results from the cache

I am using the extendedpearssisteencecontext because my entity contains a collection of child entities of deferred load type

How can I use / inject entitymanagers of type extendedpersistencecontext and create different entitymanagers in an EJB and still see the changes made by other different EJB entitymanagers?

Somewhere the entitymanagers I read should be requestscoped objects

public class MyEntityManagerProducers {
 @Produces @RequestScoped 
 public EntityManager createDbEm() {
   return Persistence.createEntityManagerFactory("forumDb").
          createEntityManager();
 }

 public void disposeUdEm(@Disposes EntityManager em) {
   em.close();
 }

Is this the way to go?

Solution

This is not a good reason to use extended I suggest you set it as the default, that is, transaction It is best to make your entitymanager request scope or method scope in a non enterprise environment or when using application managed persistence, because this is not a very important creation object Moreover, it is not a good idea to use neither application - wide entitymanager, because it is not thread - safe

Having said that, when you use JBoss, you should let the container handle the entitymanager lifecycle in case you use JTA Therefore, just inject all default values

be careful:

Only stateful session beans can have container - managed extended entity managers

Link:

> http://javanotepad.blogspot.com/2007/08/managing-jpa-entitymanager-lifecycle.html > https://blogs.oracle.com/enterprisetechtips/entry/extended_persistence_context_in_stateful

Recommendations:

Your business method should know whether to load children But that's the ideal situation Many times we can't say and it all depends on user input - we can't predict this Therefore, there are two solutions,

>Make a separate Ajax call to load children > use a filter named open session in view I prefer the former

Link:

> https://community.jboss.org/wiki/OpenSessionInView > http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html > Why is Hibernate Open Session in View considered a bad practice?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>