You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@deltaspike.apache.org by "l.penet@senat.fr" <l....@senat.fr> on 2015/04/17 11:37:17 UTC

Extended EntityManager

Dear all,

I am actually trying to switch from "raw" Hibernate to JPA.

I have the typical "keep the same entitymanager" during a scenario 
problem. IMHO, merging huge collections of entities is a nightmare that 
is not worth the cost when you deal with applications with a lot of 
business logic but few users and a low load. I fully endorse the 
"entitymanager per request" pattern for application having high trafic, 
and so need to be stateless, replicated, etc. but it does not appear to 
me to be the magic solution to all problems.

With hibernate, I historically solved it with the "open session in view" 
pattern. It is ugly when evaluated according to actual standards, but it 
works.

     https://developer.jboss.org/wiki/OpenSessionInView

When I tried to find the equivalent for JPA, I basically found

@PersistenceContext(type=PersistenceContextType.EXTENDED)

...which could be a fit if I was using container managed datasources

When digging the Hibernate 4.3.8 jpa implementation, I noticed that when I use application managed EntityManager-s, they are all created with PersistenceContextType.EXTENDED, and that this attribute is finally passed to :
AbstractEntityManagerImpl base class constructor :

	protected AbstractEntityManagerImpl(
			EntityManagerFactoryImpl entityManagerFactory,
			PersistenceContextType type,  // TODO:  remove as no longer used
			SynchronizationType synchronizationType,

and is just ignored. :-)

On this blog (I like good authors ;-) ) https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/ , I found mention of Avaje, which could be a fit if it was more of a standard.

I also fond on the net references to CODI, MyFaces Orchestra and Seam solutions to this problem. Most of the type it was also indicated that Deltaspike is "the way to go". An affirmation that is clearly also mine in general.
However, I did not find a ready-to-use solution in the doc

    http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts

I was a bit surprised, as some people stated that Seam code was to be merged in Deltaspike not to find a turn key solution.

Did I miss / misunderstood something ?

This is not a blocking problem to me. I can just use plain hibernate or unwrapped jpa/hibernate sessions and it will work... But I would like to understand. :-)

Thanks in advance,

Ludovic


|
| AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
|

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
Ok, so a pure Servlet container.

In that case you might take a look at the EntityManager-per-request pattern which I used in this sample:

https://github.com/struberg/lightweightEE

The trick is that you create a @RequestScoped EntityManager via CDI. The life span is not as long as with the em-per-session or em-per-conversation but you also have _much_ less issues with it. Of course you need to em.merge the entity to reflect your state into the DB in the callback request.

The master branch uses resource-local and there is also a JTA branch if you are running in an EE container.
I would need to upgrade this to the latest DeltaSpike version, OWB, etc (lacking a bit time here).
But in general it should work pretty fine.

Here are probably the most important parts:
https://github.com/struberg/lightweightEE/blob/master/backend/src/main/java/de/jaxenter/eesummit/caroline/backend/tools/EntityManagerProducer.java
https://github.com/struberg/lightweightEE/blob/master/backend/src/main/resources/persistence-CaroLine.properties

(you can forget about the @TransactionAware EM, you just need the @Default one)

If you like to configure your DB in another way like the default properties then you can simply provide an @Alternative PersistenceConfigurationProvider.

LieGrue,
strub


> Am 17.04.2015 um 16:53 schrieb l.penet@senat.fr:
> 
> On 17/04/2015 15:35, Mark Struberg wrote:
>> What container are you running on?
> Tomcat 8.
> 
>> And do you need JTA or ‚just‘ resource local transactions?
> I do not use JTA.
> I find all what I need with stuff like DS @Transactionnal annotation.
> 
> Best regards,
> 
> Ludovic
> |
> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
> |
> 


Re: Extended EntityManager

Posted by "l.penet@senat.fr" <l....@senat.fr>.
On 17/04/2015 15:35, Mark Struberg wrote:
> What container are you running on?
Tomcat 8.

> And do you need JTA or ‚just‘ resource local transactions?
I do not use JTA.
I find all what I need with stuff like DS @Transactionnal annotation.

Best regards,

Ludovic
|
| AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
|


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
What container are you running on? 
And do you need JTA or ‚just‘ resource local transactions?

LieGrue,
strub


> Am 17.04.2015 um 11:37 schrieb l.penet@senat.fr:
> 
> Dear all,
> 
> I am actually trying to switch from "raw" Hibernate to JPA.
> 
> I have the typical "keep the same entitymanager" during a scenario problem. IMHO, merging huge collections of entities is a nightmare that is not worth the cost when you deal with applications with a lot of business logic but few users and a low load. I fully endorse the "entitymanager per request" pattern for application having high trafic, and so need to be stateless, replicated, etc. but it does not appear to me to be the magic solution to all problems.
> 
> With hibernate, I historically solved it with the "open session in view" pattern. It is ugly when evaluated according to actual standards, but it works.
> 
>    https://developer.jboss.org/wiki/OpenSessionInView
> 
> When I tried to find the equivalent for JPA, I basically found
> 
> @PersistenceContext(type=PersistenceContextType.EXTENDED)
> 
> ...which could be a fit if I was using container managed datasources
> 
> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when I use application managed EntityManager-s, they are all created with PersistenceContextType.EXTENDED, and that this attribute is finally passed to :
> AbstractEntityManagerImpl base class constructor :
> 
> 	protected AbstractEntityManagerImpl(
> 			EntityManagerFactoryImpl entityManagerFactory,
> 			PersistenceContextType type,  // TODO:  remove as no longer used
> 			SynchronizationType synchronizationType,
> 
> and is just ignored. :-)
> 
> On this blog (I like good authors ;-) ) https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/ , I found mention of Avaje, which could be a fit if it was more of a standard.
> 
> I also fond on the net references to CODI, MyFaces Orchestra and Seam solutions to this problem. Most of the type it was also indicated that Deltaspike is "the way to go". An affirmation that is clearly also mine in general.
> However, I did not find a ready-to-use solution in the doc
> 
>   http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
> 
> I was a bit surprised, as some people stated that Seam code was to be merged in Deltaspike not to find a turn key solution.
> 
> Did I miss / misunderstood something ?
> 
> This is not a blocking problem to me. I can just use plain hibernate or unwrapped jpa/hibernate sessions and it will work... But I would like to understand. :-)
> 
> Thanks in advance,
> 
> Ludovic
> 
> 
> |
> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
> |


Re: Extended EntityManager

Posted by Gerhard Petracek <ge...@gmail.com>.
hi ludovic,

the short answer is that it's just not portable and therefore we don't
support it out-of-the-box.
however, (as you could see) our documentation describes how to do it.

regards,
gerhard



2015-04-17 11:37 GMT+02:00 l.penet@senat.fr <l....@senat.fr>:

> Dear all,
>
> I am actually trying to switch from "raw" Hibernate to JPA.
>
> I have the typical "keep the same entitymanager" during a scenario
> problem. IMHO, merging huge collections of entities is a nightmare that is
> not worth the cost when you deal with applications with a lot of business
> logic but few users and a low load. I fully endorse the "entitymanager per
> request" pattern for application having high trafic, and so need to be
> stateless, replicated, etc. but it does not appear to me to be the magic
> solution to all problems.
>
> With hibernate, I historically solved it with the "open session in view"
> pattern. It is ugly when evaluated according to actual standards, but it
> works.
>
>     https://developer.jboss.org/wiki/OpenSessionInView
>
> When I tried to find the equivalent for JPA, I basically found
>
> @PersistenceContext(type=PersistenceContextType.EXTENDED)
>
> ...which could be a fit if I was using container managed datasources
>
> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when I
> use application managed EntityManager-s, they are all created with
> PersistenceContextType.EXTENDED, and that this attribute is finally passed
> to :
> AbstractEntityManagerImpl base class constructor :
>
>         protected AbstractEntityManagerImpl(
>                         EntityManagerFactoryImpl entityManagerFactory,
>                         PersistenceContextType type,  // TODO:  remove as
> no longer used
>                         SynchronizationType synchronizationType,
>
> and is just ignored. :-)
>
> On this blog (I like good authors ;-) )
> https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/
> , I found mention of Avaje, which could be a fit if it was more of a
> standard.
>
> I also fond on the net references to CODI, MyFaces Orchestra and Seam
> solutions to this problem. Most of the type it was also indicated that
> Deltaspike is "the way to go". An affirmation that is clearly also mine in
> general.
> However, I did not find a ready-to-use solution in the doc
>
>
> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>
> I was a bit surprised, as some people stated that Seam code was to be
> merged in Deltaspike not to find a turn key solution.
>
> Did I miss / misunderstood something ?
>
> This is not a blocking problem to me. I can just use plain hibernate or
> unwrapped jpa/hibernate sessions and it will work... But I would like to
> understand. :-)
>
> Thanks in advance,
>
> Ludovic
>
>
> |
> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
> |
>

Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
2015-04-17 13:17 GMT-03:00 titou10 <ti...@gmail.com>:

> Ludovic,
> I don't know if it may be of some help for you, but we have a lot of seam2
> apps that we migrated to CDI and we had to face the problems you describe
> (With many other..)
> We tried first to use CODI then DeltaSpike, in its early days but we ended
> to create our own CDIUtils libs..
> To solve the problem, we exposed the EM in RequestScoped but it is kept
> internally a ConversationScoped Bean holder:
> So when a LRC is on, we always get the same EM
>
> @ConversationScoped
> public class EntityManagerProducer {
>    private transient EntityManager em;
>
>    @PersistenceUnit
>    private EntityManagerFactory    emf;
>
>    @Produces
>    @RequestScoped
>    protected EntityManager creerEntityManager() {
>       // On n'a pas de EM en scope conversation, on en récupère un...
>       if (em == null) {
>          em = emf.createEntityManager();
>       }
>       return this.em;
>    }
>
>    @PreDestroy
>    public void terminer() {
>       if (em != null) {
>          if (em.isOpen()) {
>             log.trace("close em {}", em);
>             em.close();
>          }
>       }
>       em = null;
>    }
> }
>
> Also the EM is not directly injected into Beans as our "Business Objects"
> are held in a jar and the jar may be used in 3 different contexts:
> - online/web in EJB3 SFSB,SLSB
> - online in MDB or Web Services beans (No conversationscope here, but
> @PersistenceUnit IS available)
> - in batchs/JUnit (No conversationscope here, and no@PersistenceUnit
> available from J2SE)
>
> We have an interface called "EMResolver" that is injected in BO beans:
> public interface EntityManagerResolver {
>    EntityManager getEm();
> }
>
> with 2 different implentations, one onlie, one for batchs (that is
> declared as an @Alternative)
> The online implementation is:
> @Stateless
> public class EntityManagerResolverOnline implements EntityManagerResolver {
>    @PersistenceContext
>    private EntityManager           emFromEJB;
>
>    @Inject
>    private Instance<EntityManager> emLazyInstance;
>
>    public EntityManager getEm() {
>       Boolean estMDBouWS = ThreadLocalContextHolder.isMDBorWS();
>       if (estMDBouWS) {
>          log.trace("Contexte online MDB ou WS - EntityManager vient de
> @PersistenceContext.");
>          return emFromEJB;
>       } else {
>          log.trace("Contexte online non MDB ni WS - EntityManager vient de
> CDI. +joinTransaction");
>          EntityManager em = emLazyInstance.get();
>          em.joinTransaction();
>          return em;
>       }
>    }
> }
> The ThreadLocalContextHolder keep a boolean "threadlocal" variable set by
> MDBs (from MDB own superclass) or WS (JAX-WS own handler)
>
> The batch implementation:
> @Alternative
> @ApplicationScoped
> public class EntityManagerBatchResolver implements EntityManagerResolver {
>
>    private EntityManagerFactory emf;
>    private EntityManager        em;
>
>    @PostConstruct
>    public void initialiser() {
>       log.debug("@PostConstruct. Utilisation de
> EntityManagerBatchResolver");
>       emf = Persistence.createEntityManagerFactory(<name of the PU here>);
>       em = emf.createEntityManager();
>    }
>
>    @PreDestroy
>    public void terminer() {
>       log.debug("@PreDestroy. terminer");
>       emf.close();
>    }
>
>    public EntityManager getEm() {
>       return em;
>    }
> }
>
> Maybe it is not very academic but it works perfectly well for us and made
> our move from seam 2 smotth..
>
> Hope this helps..
>
> Denis
>
>
> Le 2015-04-17 05:37, l.penet@senat.fr a écrit :
>
>> Dear all,
>>
>> I am actually trying to switch from "raw" Hibernate to JPA.
>>
>> I have the typical "keep the same entitymanager" during a scenario
>> problem. IMHO, merging huge collections of entities is a nightmare that is
>> not worth the cost when you deal with applications with a lot of business
>> logic but few users and a low load. I fully endorse the "entitymanager per
>> request" pattern for application having high trafic, and so need to be
>> stateless, replicated, etc. but it does not appear to me to be the magic
>> solution to all problems.
>>
>> With hibernate, I historically solved it with the "open session in view"
>> pattern. It is ugly when evaluated according to actual standards, but it
>> works.
>>
>>     https://developer.jboss.org/wiki/OpenSessionInView
>>
>> When I tried to find the equivalent for JPA, I basically found
>>
>> @PersistenceContext(type=PersistenceContextType.EXTENDED)
>>
>> ...which could be a fit if I was using container managed datasources
>>
>> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when
>> I use application managed EntityManager-s, they are all created with
>> PersistenceContextType.EXTENDED, and that this attribute is finally passed
>> to :
>> AbstractEntityManagerImpl base class constructor :
>>
>>     protected AbstractEntityManagerImpl(
>>             EntityManagerFactoryImpl entityManagerFactory,
>>             PersistenceContextType type,  // TODO:  remove as no longer
>> used
>>             SynchronizationType synchronizationType,
>>
>> and is just ignored. :-)
>>
>> On this blog (I like good authors ;-) )
>> https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/
>> , I found mention of Avaje, which could be a fit if it was more of a
>> standard.
>>
>> I also fond on the net references to CODI, MyFaces Orchestra and Seam
>> solutions to this problem. Most of the type it was also indicated that
>> Deltaspike is "the way to go". An affirmation that is clearly also mine in
>> general.
>> However, I did not find a ready-to-use solution in the doc
>>
>>
>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>
>> I was a bit surprised, as some people stated that Seam code was to be
>> merged in Deltaspike not to find a turn key solution.
>>
>> Did I miss / misunderstood something ?
>>
>> This is not a blocking problem to me. I can just use plain hibernate or
>> unwrapped jpa/hibernate sessions and it will work... But I would like to
>> understand. :-)
>>
>> Thanks in advance,
>>
>> Ludovic
>>
>>
>> |
>> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
>> |
>>
>>
>


-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
hmm, you should _not_ need to start the ApplicationContext at all. 
Is the problem in a standard Servlet Request or in some manually started Thread? (I somehow get the feeling that I miss the problem).

LieGrue,
strub

PS: have a few customers with WAS-8.5.5.3 myself, so I know pretty well what works and what not.


> Am 17.04.2015 um 19:17 schrieb Rafael Pestano <rm...@gmail.com>:
> 
> thats true:
> 
> contextControl.startContext(ApplicationScoped.class);
> 
> 
> i've overlooked Container control.
> 
> thanks karl.
> 
> 
> 2015-04-17 14:10 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> 
>> Hello, have you looked at
>> http://deltaspike.apache.org/documentation/container-control.html?
>> 
>> 
>> 
>> On 17 April 2015 at 18:51, Rafael Pestano <rm...@gmail.com> wrote:
>> 
>>> probably you can do that with OWB, but I agree that rely in proprietary
>> api
>>> is not nice....maybe if Deltaspike could activate scopes...
>>> 
>>> 2015-04-17 13:41 GMT-03:00 titou10 <ti...@gmail.com>:
>>> 
>>>> Rafael,
>>>> 
>>>> Thanks but this is not a solution for us as it uses proprietary API
>>> (Weld)
>>>> and we want to stay within the CDI 1.0 specifications.
>>>> ..and our implementation works perfectly well for our needs.
>>>> 
>>>> FYI, we deploy our apps in WebSphere v8.5.5 full profile, WAS embeds a
>>>> modified version of OWB for CDI.
>>>> 
>>>> Denis
>>>> 
>>>> 
>>>> Le 2015-04-17 12:30, Rafael Pestano a écrit :
>>>> 
>>>>> Hi Denis,
>>>>> for situations where the scope is not active we use an interceptor to
>>>>> activate it, see this example:
>>>>> 
>>>>> http://gist.asciidoctor.org/?14312d475ab402768783
>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>> 
>>> 
>>> 
>>> --
>>> <http://www.advancedit.com.br/>Att,
>>> 
>>> Rafael M. Pestano
>>> 
>>> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
>>> http://rpestano.wordpress.com/
>>> @realpestano <https://twitter.com/realpestano>
>>> 
>> 
> 
> 
> 
> -- 
> <http://www.advancedit.com.br/>Att,
> 
> Rafael M. Pestano
> 
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>


Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
thats true:

 contextControl.startContext(ApplicationScoped.class);


i've overlooked Container control.

thanks karl.


2015-04-17 14:10 GMT-03:00 Karl Kildén <ka...@gmail.com>:

> Hello, have you looked at
> http://deltaspike.apache.org/documentation/container-control.html?
>
>
>
> On 17 April 2015 at 18:51, Rafael Pestano <rm...@gmail.com> wrote:
>
> > probably you can do that with OWB, but I agree that rely in proprietary
> api
> > is not nice....maybe if Deltaspike could activate scopes...
> >
> > 2015-04-17 13:41 GMT-03:00 titou10 <ti...@gmail.com>:
> >
> > > Rafael,
> > >
> > > Thanks but this is not a solution for us as it uses proprietary API
> > (Weld)
> > > and we want to stay within the CDI 1.0 specifications.
> > > ..and our implementation works perfectly well for our needs.
> > >
> > > FYI, we deploy our apps in WebSphere v8.5.5 full profile, WAS embeds a
> > > modified version of OWB for CDI.
> > >
> > > Denis
> > >
> > >
> > > Le 2015-04-17 12:30, Rafael Pestano a écrit :
> > >
> > >> Hi Denis,
> > >> for situations where the scope is not active we use an interceptor to
> > >> activate it, see this example:
> > >>
> > >> http://gist.asciidoctor.org/?14312d475ab402768783
> > >>
> > >>
> > >>
> > >>
> > >
> >
> >
> > --
> > <http://www.advancedit.com.br/>Att,
> >
> > Rafael M. Pestano
> >
> > Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> > http://rpestano.wordpress.com/
> > @realpestano <https://twitter.com/realpestano>
> >
>



-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Karl Kildén <ka...@gmail.com>.
Hello, have you looked at
http://deltaspike.apache.org/documentation/container-control.html?



On 17 April 2015 at 18:51, Rafael Pestano <rm...@gmail.com> wrote:

> probably you can do that with OWB, but I agree that rely in proprietary api
> is not nice....maybe if Deltaspike could activate scopes...
>
> 2015-04-17 13:41 GMT-03:00 titou10 <ti...@gmail.com>:
>
> > Rafael,
> >
> > Thanks but this is not a solution for us as it uses proprietary API
> (Weld)
> > and we want to stay within the CDI 1.0 specifications.
> > ..and our implementation works perfectly well for our needs.
> >
> > FYI, we deploy our apps in WebSphere v8.5.5 full profile, WAS embeds a
> > modified version of OWB for CDI.
> >
> > Denis
> >
> >
> > Le 2015-04-17 12:30, Rafael Pestano a écrit :
> >
> >> Hi Denis,
> >> for situations where the scope is not active we use an interceptor to
> >> activate it, see this example:
> >>
> >> http://gist.asciidoctor.org/?14312d475ab402768783
> >>
> >>
> >>
> >>
> >
>
>
> --
> <http://www.advancedit.com.br/>Att,
>
> Rafael M. Pestano
>
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>
>

Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
probably you can do that with OWB, but I agree that rely in proprietary api
is not nice....maybe if Deltaspike could activate scopes...

2015-04-17 13:41 GMT-03:00 titou10 <ti...@gmail.com>:

> Rafael,
>
> Thanks but this is not a solution for us as it uses proprietary API (Weld)
> and we want to stay within the CDI 1.0 specifications.
> ..and our implementation works perfectly well for our needs.
>
> FYI, we deploy our apps in WebSphere v8.5.5 full profile, WAS embeds a
> modified version of OWB for CDI.
>
> Denis
>
>
> Le 2015-04-17 12:30, Rafael Pestano a écrit :
>
>> Hi Denis,
>> for situations where the scope is not active we use an interceptor to
>> activate it, see this example:
>>
>> http://gist.asciidoctor.org/?14312d475ab402768783
>>
>>
>>
>>
>


-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
Rafael,

Thanks but this is not a solution for us as it uses proprietary API (Weld) and we want to stay within the CDI 1.0 specifications.
..and our implementation works perfectly well for our needs.

FYI, we deploy our apps in WebSphere v8.5.5 full profile, WAS embeds a modified version of OWB for CDI.

Denis

Le 2015-04-17 12:30, Rafael Pestano a écrit :
> Hi Denis,
> for situations where the scope is not active we use an interceptor to
> activate it, see this example:
>
> http://gist.asciidoctor.org/?14312d475ab402768783
>
>
>


Re: Extended EntityManager

Posted by PÉNET LUDOVIC <l....@senat.fr>.
Mark Struberg a écrit :
> Hi Ludovic!
>
> One possible solution is the locking as you already explained.
> Another one which worked well for me is to wrap JSF sendRedirect and close
> the EM in there. Would need to think how we can make this solution more
> broad and generally available.
> A third solution would theoretically be to ‚postpone‘ the redirect
> until the end of the request.
>
> This is surely an area where we could make it a LOT easier for Seam2 users
> (and other CRUD style projects) to get their apps ported over to CDI.
> So any ideas, objections and tricks are welcome :)
The three possibilities you mention look pretty similar to me. In all
cases, the goal is to have one and only one "JSF thread" at a time.

So, you just let go resource queries, other servlet queries but lock on
JSF queries.

In the implementation I use for "open view conversation" pattern, I
recognize "true" JSF requests by the fact they have a dswid parameter.

If this parameter is not set, I just pass the query to the next layer,
else I lock on the http session (and not the hibernate session as I
wrongly stated before).

Something like :

public class SequentialJSFQueriesFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpreq = (HttpServletRequest)request;
        String dswid = httpreq.getParameter("dswid");
        if (StringUtils.isEmpty(dswid)) {
            chain.doFilter(request, response);
            return;
        }


        HttpSession httpSession = httpreq.getSession();
        try {
            if (httpSession != null) {
                synchronized(httpSession) {
                    chain.doFilter(request, response);
                }
            }
        } catch(...) {
	  /// ...
        }
    }
}

The performance impact is not that bad. Of course, it would be better
without locking, but keeping the same DB session also has its own
advantages. And it allows you to go the easy way, such as keeping DTOs and
serializing them in the session. You can heavily use features such as
cascading operations without fearing horrible side effects - those who one
day "merged" objects in a complex hierarchy, then "updated" them and
accidentally deleted dozens of "cascading dependencies" know what I mean.
:->

And, well, again, if you know you are coding a demanding application, with
a high workload, a need for replication, and so on, you just don't go that
way. :-)

Of course, a custom implementation can add the little bells and whistles
some application needs, still to go the easy way. In my case, I also
handle for instance a "nokeepsession" parameter, which I use to invalidate
the http session once the request has been processed. Some of my
applications are used to batch generate thousands of static pages. With
this kind of simple trick, I have an easy mean to quickly close useless
http sessions.

Ludovic

|
| AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
|


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
Hi Ludovic!

One possible solution is the locking as you already explained. 
Another one which worked well for me is to wrap JSF sendRedirect and close the EM in there. Would need to think how we can make this solution more broad and generally available.
A third solution would theoretically be to ‚postpone‘ the redirect until the end of the request. 

This is surely an area where we could make it a LOT easier for Seam2 users (and other CRUD style projects) to get their apps ported over to CDI.
So any ideas, objections and tricks are welcome :)

LieGrue,
strub


> Am 19.04.2015 um 21:02 schrieb Ludovic Pénet <l....@senat.fr>:
> 
> Well, I experienced very often this kind of bug even with a simple filter implementing open view scope pattern.
> 
> My (violent but efficient) fix was to lock on the hibernate session before passing the request to the next layer.
> 
> So, I take Mark warning very seriously.
> 
> And, Mark, is there something preventing such undesired behaviour if I stick with the proposal on DS JPA module page with a production of a @ViewAccessScoped EM ? Can I take for granted that only one thread at a time will be allowed or would I better backpedal immediatly to @RequestScoped (or toy with a filter to both lock and provide a ready for injection EM) ?
> 
> Ludovic
> 
> Le 19 avril 2015 17:24:08 UTC+02:00, Mark Struberg <st...@yahoo.de> a écrit :
>> Hi Dennis!
>> 
>> 
>>> Have you *ever* hit this situation?
>> Yes, under heavy load it happens pretty often actually (I’m talking
>> about multi-million request/day public internet apps). It also depends
>> a bit on the JPA container you use. From the pure spec it is forbitten
>> to touch the EntityManager in parallel threads and also to touch
>> managed (‚attached’) entities in parallel threads. What JPA container
>> are you using?
>> 
>> 
>>> Also, who programs a „sendRedirect" in the middle of a method that
>> then performs database access ..?
>> 
>> You don’t need to do database access even. It is enough that the
>> entitymanager is not closed as per the spec.
>> 
>> 
>>> Even so, this is pure theory, the chance are so tiny this happens…
>> Then I had bad luck - quite often ;)
>> 
>> 
>>> And If you think this *may* happen within one conversation, then
>> change the way redirects are send, or the way database is accessed in
>> parallel in Ajax requests. not the way EM is used IMHO
>> 
>> That might be a solution. Or force the EM to get closed before the
>> redirect.
>> 
>>> Also your remark on „unfinished thread" is valid for ANY
>> components/resources held in ConversationScope, not just the EM, true?
>> 
>> Yes, but most components have no problems with getting accessed in
>> parallel. For managed Entities and EntityManagers it’s explicitly
>> forbidden by the JPA spec.
>> 
>> LieGrue,
>> strub
> 
> -- 
> Envoyé de mon téléphone Android avec K-9 Mail. Excusez la brièveté.
> |
> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
> |


Re: Extended EntityManager

Posted by Ludovic Pénet <l....@senat.fr>.
Well, I experienced very often this kind of bug even with a simple filter implementing open view scope pattern.

My (violent but efficient) fix was to lock on the hibernate session before passing the request to the next layer.

So, I take Mark warning very seriously.

And, Mark, is there something preventing such undesired behaviour if I stick with the proposal on DS JPA module page with a production of a @ViewAccessScoped EM ? Can I take for granted that only one thread at a time will be allowed or would I better backpedal immediatly to @RequestScoped (or toy with a filter to both lock and provide a ready for injection EM) ?

Ludovic

Le 19 avril 2015 17:24:08 UTC+02:00, Mark Struberg <st...@yahoo.de> a écrit :
>Hi Dennis!
>
>
>> Have you *ever* hit this situation?
>Yes, under heavy load it happens pretty often actually (I’m talking
>about multi-million request/day public internet apps). It also depends
>a bit on the JPA container you use. From the pure spec it is forbitten
>to touch the EntityManager in parallel threads and also to touch
>managed (‚attached’) entities in parallel threads. What JPA container
>are you using?
>
>
>> Also, who programs a „sendRedirect" in the middle of a method that
>then performs database access ..?
>
>You don’t need to do database access even. It is enough that the
>entitymanager is not closed as per the spec.
>
>
>> Even so, this is pure theory, the chance are so tiny this happens…
>Then I had bad luck - quite often ;)
>
>
>> And If you think this *may* happen within one conversation, then
>change the way redirects are send, or the way database is accessed in
>parallel in Ajax requests. not the way EM is used IMHO
>
>That might be a solution. Or force the EM to get closed before the
>redirect.
>
>> Also your remark on „unfinished thread" is valid for ANY
>components/resources held in ConversationScope, not just the EM, true?
>
>Yes, but most components have no problems with getting accessed in
>parallel. For managed Entities and EntityManagers it’s explicitly
>forbidden by the JPA spec.
>
>LieGrue,
>strub

-- 
Envoyé de mon téléphone Android avec K-9 Mail. Excusez la brièveté.
|
| AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
|

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
I guess we have a slightly different picture of what we do.

A Conversation per definition is a part of a Session. A Http Session can contain multiple CDI Conversations. But a CDI Conversation can NEVER span HttpSessions of different users. So each user always has a different Conversation. 
Are we d’accord so far?

And no, I don’t have this often, but it _does_ happen. And you don’t even need Ajax for it. It works with simply redirects to another JSF page. 

> Or you are talking about *not closed EM* because the @PreDestroy callback method has not been called in some particulat situation (sendRedirect is called and the new request is processed before the initial request)?

This is precisely what _sometimes_ (again, not often) happens. The point is that the new request (the redirected one) gets served by a different thread while the original thread still needs to finish his work. It will not often happen if you use DTOs but you might get this case more often if you store entities directly in your conversation (Another symptom of the same underlying problem). 

LieGrue,
strub


> Am 19.04.2015 um 19:20 schrieb titou10 <ti...@gmail.com>:
> 
> 
> 
> Le 2015-04-19 11:24, Mark Struberg a écrit :
>> Hi Dennis!
>> 
>> 
>>> Have you *ever* hit this situation?
>> Yes, under heavy load it happens pretty often actually (I’m talking about multi-million request/day public internet apps). It also depends a bit on the JPA container you use. From the pure spec it is forbitten to touch the EntityManager in parallel threads and also to touch managed (‚attached’) entities in parallel threads. What JPA container are you using?
> Here we are talking about one ONE EM per ONE CDI Conversation.
> So you have  applications with multi-million request/day concurrently in one CDI Conversation that may lead *often* to a misuse of the EM ?
> Impressive... How do you do that: Ajax requests? Proprietary client javascript framework?
> Or you are talking about *not closed EM* because the @PreDestroy callback method has not been called in some particulat situation (sendRedirect is called and the new request is processed before the initial request)?
> Sorry, Mark but you lost me.....
> Denis
> 
>>> Also, who programs a „sendRedirect" in the middle of a method that then performs database access ..?
>> You don’t need to do database access even. It is enough that the entitymanager is not closed as per the spec.
>> 
>> 
>>> Even so, this is pure theory, the chance are so tiny this happens…
>> Then I had bad luck - quite often ;)
>> 
>> 
>>> And If you think this *may* happen within one conversation, then change the way redirects are send, or the way database is accessed in parallel in Ajax requests. not the way EM is used IMHO
>> That might be a solution. Or force the EM to get closed before the redirect.
>> 
>>> Also your remark on „unfinished thread" is valid for ANY components/resources held in ConversationScope, not just the EM, true?
>> Yes, but most components have no problems with getting accessed in parallel. For managed Entities and EntityManagers it’s explicitly forbidden by the JPA spec.
>> 
>> LieGrue,
>> strub
> 


Re: Extended EntityManager

Posted by titou10 titou10 <ti...@gmail.com>.
I totally agree with Rafael, you can't say that the EJB model is
broken because you don't use it the right way it is supposed to be
used.

As for other frameworks, they are rules and the ones around the EJB
paradigm they are not so bad IMHO

Your example is simplistic IMHO, in real life you'll want to catch the
exception and react to it, e.g. by displaying a nice message to the
end user instead of letting the container generic exception handler to
take care of it, and decide to rollback or not the transaction (or
take other actions). Maybe is is a problem for you because your
backing beans are not EJB, but servlets that do not control the
transaction.

In our apps, we are EJB3 and CDI all the way and it works very well.
Basically we have 3 layers:

- backing beans (aka "View Controllers"), mostly SFSB, in ViewScoped
or ConversationScoped), exposed to JSF. Usually

- "managers", that implements business logic, handles access to the
database etc (Always SLSB, not exposed to JSF, only called from "View
Controllers")

- Entities (JPA, Hibernate), detached, may be directly exposed to JSF.
No need for DTO or so called transport objects..

- the EM is held in the Conversation scoped and exposed in the
RequestScoped as explained before, transactions are managed by the
EJB3 Containers, no need for extra filters etc.

View Controllers react to user actions, manage navigation, call
managers for business logic, catch exceptions raised from them, and
usually in this case call "setRollbackOnly" and display a nice message
to the end-user.

As a  "security net", the "global container exception handler"
performs a transaction rollback in case an exception comes up there
with a still active transaction before displaying a "generic error
page". "em.flush()" is called judiciously in the view Controller to
catch potential db exceptions before letting the container commit at
the end of the initial method called.

We already talks about this months ago in some forum. It is your right
to claim that the EJB paradigm is broken (and you clearly have the
authority/experience/legitimity etc to do it.), but as Rafael said, it
strangely works very well for many many applications when you follow
the way it is meant to be, including  us, and for many other people
that use it also.

Previously, the (your) arguments against our architecture, was that a
lot of (useless) transactions are started on each page because of the
calls to the SFSB View Controller (eg getters). But what we've seen in
real life, at least in WebSphere v8.5, is that this is negligible as
the Container seems to be optimized to do the costly job around
transactions only when a resource manager (the EM) is really "used"
during the request

This architecture also gives a "clear straight path" from Seam 2/JSF
1.2 to CDI/JSF2.0, but I understand that people may want to move away
from it.

Clearly, there are two schools here, one with EJB and one without.
Both have advantages and drawbacks IMHO..and there is not just one way

Seam 2 attracted us because it simplified things and simplified code
layers, and we continue to use the same paradigm with CDI now, JSF
2.0, and  EJB3, as in Seam 2. Very fast to develop, easy to understand
and maintain, no proprietary framework in the way, no performance
problem or other problems.

On another subject, thanks for your blog Mark, which is always
interesting to read.

Cheers, choice is fun!

Denis

(Please view this post as way to bring another constructive brick to
the discussion and not for anything else)



2015-04-21 7:07 GMT-04:00 Rafael Pestano <rm...@gmail.com>:
> Hi Mark,
>
> i don't think it's broken but i agree with CODI/DS transaction management
> superiority, in fact i've using it for years on my personal projects
> <https://github.com/rmpestano/jsf-issuetracker-project/blob/master/src/br/com/triadworks/issuetracker/dao/impl/IssueDaoImpl.java>
> but use EJBs on my company and don't think its broken, even for high load
> application.
>
> Congrats for the post.

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
Hi!

It’s not technically broken IF you know what you do. What I tried to emphase is that it is really hard to get right for people who are not that deep into that stuff like we are. 
I’ve seen this handled correctly in 3 out of 10 projects. Means 7 out of 10 projects are having troubles in their error handling chains or potentially creating inconsistent data.

LieGrue,
strub


> Am 21.04.2015 um 13:07 schrieb Rafael Pestano <rm...@gmail.com>:
> 
> Hi Mark,
> 
> i don't think it's broken but i agree with CODI/DS transaction management
> superiority, in fact i've using it for years on my personal projects
> <https://github.com/rmpestano/jsf-issuetracker-project/blob/master/src/br/com/triadworks/issuetracker/dao/impl/IssueDaoImpl.java>
> but use EJBs on my company and don't think its broken, even for high load
> application.
> 
> Congrats for the post.
> 
> 
> 2015-04-21 4:02 GMT-03:00 Mark Struberg <st...@yahoo.de>:
> 
>> And here it comes:
>> 
>> 
>> https://struberg.wordpress.com/2015/04/21/transaction-and-exception-handling-in-ejbs-and-javaee7-transactional/
>> 
>> Feedback and corrections are much appreciated!
>> 
>> LieGrue,
>> strub
>> 
>> 
>>> Am 20.04.2015 um 19:58 schrieb Mark Struberg <st...@yahoo.de>:
>>> 
>>> You can do the same with DeltaSpike @Transactional and
>> @TransactionScoped EntityManagers ;)
>>> 
>>> The difference is subtle but very important. Imo the EE7
>> javax.transaction.Transactional is as broken as EJB transactions if you
>> build big real world apps (banks, insurance companies, government projects,
>> etc).
>>> I really dislike the Exception handling in EJB and EE7 @Transactional.
>> It’s soooo weird and most people are not aware how it works. I probably
>> really should write up another blog post.
>>> 
>>> LieGrue,
>>> strub
>>> 
>>>> Am 20.04.2015 um 17:14 schrieb Cody Lerum <co...@gmail.com>:
>>>> 
>>>> FWIW I started developing my application on Seam 2 with it's
>>>> Conversation scoped EntityManager. Everything was so simple and
>>>> everything worked, but my application was also very small at the time
>>>> and everything was invoked by a user clicking a button or a link in a
>>>> JSF page.
>>>> 
>>>> Over time my application grew to have JAX-WS and JAX-RS and timers. It
>>>> also migrated from Seam to EE6/CDI. Since there are no Conversations
>>>> during these types of requests this created issues and hacky
>>>> workarounds. Eventually I converted to a RequestScoped EntityManager
>>>> and everything was simple except for lazy loading and merging.
>>>> 
>>>> Over more time my application started to pick up some batch type
>>>> processing requirements where I wanted to operate on multiple
>>>> transactions within a single request which may be invoked from many
>>>> different places.  I migrated to EE7 and converted to a EM per
>>>> transaction. It is a bit more work to ensure that you merge and
>>>> trigger lazy loads, but I feel that it gives me a lot of flexibility
>>>> and removes a lot of limitations.
>>>> 
>>>> In my experience the extended EntityManagers can be a great time
>>>> savings in initial app development, but they are also potential long
>>>> term technical debt if your application keeps growing and introducing
>>>> new requirements. I would just recommend that you really understand
>>>> the context you are using (Session, Conversation, Request,
>>>> Transaction) and know about when these contexts are and aren't created
>>>> (and destroyed).
>>>> 
>>>> -C
>>>> 
>>>> On Sun, Apr 19, 2015 at 9:46 PM, Rafael Pestano <rm...@gmail.com>
>> wrote:
>>>>> reading this topic gives me the sensation that there are more "cons"
>> then
>>>>> "pros" when using an extended entity manager.
>>>>> 
>>>>> Besides avoiding Lazy initialization exceptions by letting the EM open
>> in
>>>>> eg master detail views where else going stateful is really
>> advantageous?
>>>>> 
>>>>> I've been working with stateless EM quite a lot and never needed an OSI
>>>>> filter, doing extra queries for fetching always did the trick.
>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>>> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
>>>>> 
>>>>>> Thanks, feels obvious now when you said it. Off topic but for my apps
>> Marks
>>>>>> old suggestion on his blog to optionally drop pessimistic locking and
>> make
>>>>>> it Serializable would be perfect for my apps.
>>>>>> 
>>>>>> 
>>>>>> 
>>>>>> 
>>>>>> 
>>>>>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>>>>>> 
>>>>>>> Karl,
>>>>>>> 
>>>>>>> Mostly because ConversationScope beans must be serializable and the
>> EM is
>>>>>>> not (check the "transient" keyword on the variable that keeps in the
>>>>>>> ConversationScope Holder) and the fact that in our web apps, the EM
>> can
>>>>>> be
>>>>>>> injected in components where the ConversationScope is not active
>> (Namely
>>>>>>> MDBs and JAX-WS endpoints), where there is only one "request" and no
>> need
>>>>>>> to get the same EM. For this we use another layer (Check my previous
>>>>>> posts
>>>>>>> about our the "EntityResolver" interface and implementations)
>>>>>>> 
>>>>>>> Denis
>>>>>>> 
>>>>>>> 
>>>>>>> Le 2015-04-19 14:33, Karl Kildén a écrit :
>>>>>>> 
>>>>>>>> Denis,
>>>>>>>> 
>>>>>>>> What's the added benefit of wrapping the em in @ConversationScoped
>>>>>> instead
>>>>>>>> of exposing it like this directly. I am also porting a huge seam app
>>>>>>>> (about
>>>>>>>> 1k views) so I do need extended em.
>>>>>>>> 
>>>>>>>> cheers
>>>>>>>> 
>>>>>>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com>
>> wrote:
>>>>>>>> 
>>>>>>>> 
>>>>>>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>>>>>>>> 
>>>>>>>>> Hi Dennis!
>>>>>>>>>> 
>>>>>>>>>> 
>>>>>>>>>> Have you *ever* hit this situation?
>>>>>>>>>> Yes, under heavy load it happens pretty often actually (I’m
>> talking
>>>>>>>>>> about
>>>>>>>>>> multi-million request/day public internet apps). It also depends
>> a bit
>>>>>>>>>> on
>>>>>>>>>> the JPA container you use. From the pure spec it is forbitten to
>> touch
>>>>>>>>>> the
>>>>>>>>>> EntityManager in parallel threads and also to touch managed
>>>>>> (‚attached’)
>>>>>>>>>> entities in parallel threads. What JPA container are you using?
>>>>>>>>>> 
>>>>>>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
>>>>>>>>> So you have  applications with multi-million request/day
>> concurrently
>>>>>> in
>>>>>>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>>>>>>>>> Impressive... How do you do that: Ajax requests? Proprietary client
>>>>>>>>> javascript framework?
>>>>>>>>> Or you are talking about *not closed EM* because the @PreDestroy
>>>>>> callback
>>>>>>>>> method has not been called in some particulat situation
>> (sendRedirect
>>>>>> is
>>>>>>>>> called and the new request is processed before the initial
>> request)?
>>>>>>>>> Sorry, Mark but you lost me.....
>>>>>>>>> Denis
>>>>>>>>> 
>>>>>>>>> 
>>>>>>>>> Also, who programs a „sendRedirect" in the middle of a method that
>>>>>> then
>>>>>>>>> 
>>>>>>>>>> performs database access ..?
>>>>>>>>>>> 
>>>>>>>>>>> You don’t need to do database access even. It is enough that the
>>>>>>>>>> entitymanager is not closed as per the spec.
>>>>>>>>>> 
>>>>>>>>>> 
>>>>>>>>>> Even so, this is pure theory, the chance are so tiny this happens…
>>>>>>>>>> Then I had bad luck - quite often ;)
>>>>>>>>>> 
>>>>>>>>>> 
>>>>>>>>>> And If you think this *may* happen within one conversation, then
>>>>>>>>>> change
>>>>>>>>>> 
>>>>>>>>>>> the way redirects are send, or the way database is accessed in
>>>>>>>>>>> parallel in
>>>>>>>>>>> Ajax requests. not the way EM is used IMHO
>>>>>>>>>>> 
>>>>>>>>>>> That might be a solution. Or force the EM to get closed before
>> the
>>>>>>>>>> redirect.
>>>>>>>>>> 
>>>>>>>>>> Also your remark on „unfinished thread" is valid for ANY
>>>>>>>>>> 
>>>>>>>>>>> components/resources held in ConversationScope, not just the EM,
>>>>>> true?
>>>>>>>>>>> 
>>>>>>>>>>> Yes, but most components have no problems with getting accessed
>> in
>>>>>>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
>>>>>>>>>> forbidden
>>>>>>>>>> by the JPA spec.
>>>>>>>>>> 
>>>>>>>>>> LieGrue,
>>>>>>>>>> strub
>>>>>>>>>> 
>>>>>>>>>> 
>>>>>>>>> 
>>>>>>> 
>>>>>> 
>>>>> 
>>>>> 
>>>>> 
>>>>> --
>>>>> <http://www.advancedit.com.br/>Att,
>>>>> 
>>>>> Rafael M. Pestano
>>>>> 
>>>>> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
>>>>> http://rpestano.wordpress.com/
>>>>> @realpestano <https://twitter.com/realpestano>
>>> 
>> 
>> 
> 
> 
> -- 
> <http://www.advancedit.com.br/>Att,
> 
> Rafael M. Pestano
> 
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>


Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
Hi Mark,

i don't think it's broken but i agree with CODI/DS transaction management
superiority, in fact i've using it for years on my personal projects
<https://github.com/rmpestano/jsf-issuetracker-project/blob/master/src/br/com/triadworks/issuetracker/dao/impl/IssueDaoImpl.java>
but use EJBs on my company and don't think its broken, even for high load
application.

Congrats for the post.


2015-04-21 4:02 GMT-03:00 Mark Struberg <st...@yahoo.de>:

> And here it comes:
>
>
> https://struberg.wordpress.com/2015/04/21/transaction-and-exception-handling-in-ejbs-and-javaee7-transactional/
>
> Feedback and corrections are much appreciated!
>
> LieGrue,
> strub
>
>
> > Am 20.04.2015 um 19:58 schrieb Mark Struberg <st...@yahoo.de>:
> >
> > You can do the same with DeltaSpike @Transactional and
> @TransactionScoped EntityManagers ;)
> >
> > The difference is subtle but very important. Imo the EE7
> javax.transaction.Transactional is as broken as EJB transactions if you
> build big real world apps (banks, insurance companies, government projects,
> etc).
> > I really dislike the Exception handling in EJB and EE7 @Transactional.
> It’s soooo weird and most people are not aware how it works. I probably
> really should write up another blog post.
> >
> > LieGrue,
> > strub
> >
> >> Am 20.04.2015 um 17:14 schrieb Cody Lerum <co...@gmail.com>:
> >>
> >> FWIW I started developing my application on Seam 2 with it's
> >> Conversation scoped EntityManager. Everything was so simple and
> >> everything worked, but my application was also very small at the time
> >> and everything was invoked by a user clicking a button or a link in a
> >> JSF page.
> >>
> >> Over time my application grew to have JAX-WS and JAX-RS and timers. It
> >> also migrated from Seam to EE6/CDI. Since there are no Conversations
> >> during these types of requests this created issues and hacky
> >> workarounds. Eventually I converted to a RequestScoped EntityManager
> >> and everything was simple except for lazy loading and merging.
> >>
> >> Over more time my application started to pick up some batch type
> >> processing requirements where I wanted to operate on multiple
> >> transactions within a single request which may be invoked from many
> >> different places.  I migrated to EE7 and converted to a EM per
> >> transaction. It is a bit more work to ensure that you merge and
> >> trigger lazy loads, but I feel that it gives me a lot of flexibility
> >> and removes a lot of limitations.
> >>
> >> In my experience the extended EntityManagers can be a great time
> >> savings in initial app development, but they are also potential long
> >> term technical debt if your application keeps growing and introducing
> >> new requirements. I would just recommend that you really understand
> >> the context you are using (Session, Conversation, Request,
> >> Transaction) and know about when these contexts are and aren't created
> >> (and destroyed).
> >>
> >> -C
> >>
> >> On Sun, Apr 19, 2015 at 9:46 PM, Rafael Pestano <rm...@gmail.com>
> wrote:
> >>> reading this topic gives me the sensation that there are more "cons"
> then
> >>> "pros" when using an extended entity manager.
> >>>
> >>> Besides avoiding Lazy initialization exceptions by letting the EM open
> in
> >>> eg master detail views where else going stateful is really
> advantageous?
> >>>
> >>> I've been working with stateless EM quite a lot and never needed an OSI
> >>> filter, doing extra queries for fetching always did the trick.
> >>>
> >>>
> >>>
> >>>
> >>> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> >>>
> >>>> Thanks, feels obvious now when you said it. Off topic but for my apps
> Marks
> >>>> old suggestion on his blog to optionally drop pessimistic locking and
> make
> >>>> it Serializable would be perfect for my apps.
> >>>>
> >>>>
> >>>>
> >>>>
> >>>>
> >>>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
> >>>>
> >>>>> Karl,
> >>>>>
> >>>>> Mostly because ConversationScope beans must be serializable and the
> EM is
> >>>>> not (check the "transient" keyword on the variable that keeps in the
> >>>>> ConversationScope Holder) and the fact that in our web apps, the EM
> can
> >>>> be
> >>>>> injected in components where the ConversationScope is not active
> (Namely
> >>>>> MDBs and JAX-WS endpoints), where there is only one "request" and no
> need
> >>>>> to get the same EM. For this we use another layer (Check my previous
> >>>> posts
> >>>>> about our the "EntityResolver" interface and implementations)
> >>>>>
> >>>>> Denis
> >>>>>
> >>>>>
> >>>>> Le 2015-04-19 14:33, Karl Kildén a écrit :
> >>>>>
> >>>>>> Denis,
> >>>>>>
> >>>>>> What's the added benefit of wrapping the em in @ConversationScoped
> >>>> instead
> >>>>>> of exposing it like this directly. I am also porting a huge seam app
> >>>>>> (about
> >>>>>> 1k views) so I do need extended em.
> >>>>>>
> >>>>>> cheers
> >>>>>>
> >>>>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com>
> wrote:
> >>>>>>
> >>>>>>
> >>>>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
> >>>>>>>
> >>>>>>> Hi Dennis!
> >>>>>>>>
> >>>>>>>>
> >>>>>>>> Have you *ever* hit this situation?
> >>>>>>>> Yes, under heavy load it happens pretty often actually (I’m
> talking
> >>>>>>>> about
> >>>>>>>> multi-million request/day public internet apps). It also depends
> a bit
> >>>>>>>> on
> >>>>>>>> the JPA container you use. From the pure spec it is forbitten to
> touch
> >>>>>>>> the
> >>>>>>>> EntityManager in parallel threads and also to touch managed
> >>>> (‚attached’)
> >>>>>>>> entities in parallel threads. What JPA container are you using?
> >>>>>>>>
> >>>>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
> >>>>>>> So you have  applications with multi-million request/day
> concurrently
> >>>> in
> >>>>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
> >>>>>>> Impressive... How do you do that: Ajax requests? Proprietary client
> >>>>>>> javascript framework?
> >>>>>>> Or you are talking about *not closed EM* because the @PreDestroy
> >>>> callback
> >>>>>>> method has not been called in some particulat situation
> (sendRedirect
> >>>> is
> >>>>>>> called and the new request is processed before the initial
> request)?
> >>>>>>> Sorry, Mark but you lost me.....
> >>>>>>> Denis
> >>>>>>>
> >>>>>>>
> >>>>>>> Also, who programs a „sendRedirect" in the middle of a method that
> >>>> then
> >>>>>>>
> >>>>>>>> performs database access ..?
> >>>>>>>>>
> >>>>>>>>> You don’t need to do database access even. It is enough that the
> >>>>>>>> entitymanager is not closed as per the spec.
> >>>>>>>>
> >>>>>>>>
> >>>>>>>> Even so, this is pure theory, the chance are so tiny this happens…
> >>>>>>>> Then I had bad luck - quite often ;)
> >>>>>>>>
> >>>>>>>>
> >>>>>>>> And If you think this *may* happen within one conversation, then
> >>>>>>>> change
> >>>>>>>>
> >>>>>>>>> the way redirects are send, or the way database is accessed in
> >>>>>>>>> parallel in
> >>>>>>>>> Ajax requests. not the way EM is used IMHO
> >>>>>>>>>
> >>>>>>>>> That might be a solution. Or force the EM to get closed before
> the
> >>>>>>>> redirect.
> >>>>>>>>
> >>>>>>>> Also your remark on „unfinished thread" is valid for ANY
> >>>>>>>>
> >>>>>>>>> components/resources held in ConversationScope, not just the EM,
> >>>> true?
> >>>>>>>>>
> >>>>>>>>> Yes, but most components have no problems with getting accessed
> in
> >>>>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
> >>>>>>>> forbidden
> >>>>>>>> by the JPA spec.
> >>>>>>>>
> >>>>>>>> LieGrue,
> >>>>>>>> strub
> >>>>>>>>
> >>>>>>>>
> >>>>>>>
> >>>>>
> >>>>
> >>>
> >>>
> >>>
> >>> --
> >>> <http://www.advancedit.com.br/>Att,
> >>>
> >>> Rafael M. Pestano
> >>>
> >>> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> >>> http://rpestano.wordpress.com/
> >>> @realpestano <https://twitter.com/realpestano>
> >
>
>


-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
And here it comes:

https://struberg.wordpress.com/2015/04/21/transaction-and-exception-handling-in-ejbs-and-javaee7-transactional/

Feedback and corrections are much appreciated!

LieGrue,
strub


> Am 20.04.2015 um 19:58 schrieb Mark Struberg <st...@yahoo.de>:
> 
> You can do the same with DeltaSpike @Transactional and @TransactionScoped EntityManagers ;)
> 
> The difference is subtle but very important. Imo the EE7 javax.transaction.Transactional is as broken as EJB transactions if you build big real world apps (banks, insurance companies, government projects, etc). 
> I really dislike the Exception handling in EJB and EE7 @Transactional. It’s soooo weird and most people are not aware how it works. I probably really should write up another blog post.
> 
> LieGrue,
> strub
> 
>> Am 20.04.2015 um 17:14 schrieb Cody Lerum <co...@gmail.com>:
>> 
>> FWIW I started developing my application on Seam 2 with it's
>> Conversation scoped EntityManager. Everything was so simple and
>> everything worked, but my application was also very small at the time
>> and everything was invoked by a user clicking a button or a link in a
>> JSF page.
>> 
>> Over time my application grew to have JAX-WS and JAX-RS and timers. It
>> also migrated from Seam to EE6/CDI. Since there are no Conversations
>> during these types of requests this created issues and hacky
>> workarounds. Eventually I converted to a RequestScoped EntityManager
>> and everything was simple except for lazy loading and merging.
>> 
>> Over more time my application started to pick up some batch type
>> processing requirements where I wanted to operate on multiple
>> transactions within a single request which may be invoked from many
>> different places.  I migrated to EE7 and converted to a EM per
>> transaction. It is a bit more work to ensure that you merge and
>> trigger lazy loads, but I feel that it gives me a lot of flexibility
>> and removes a lot of limitations.
>> 
>> In my experience the extended EntityManagers can be a great time
>> savings in initial app development, but they are also potential long
>> term technical debt if your application keeps growing and introducing
>> new requirements. I would just recommend that you really understand
>> the context you are using (Session, Conversation, Request,
>> Transaction) and know about when these contexts are and aren't created
>> (and destroyed).
>> 
>> -C
>> 
>> On Sun, Apr 19, 2015 at 9:46 PM, Rafael Pestano <rm...@gmail.com> wrote:
>>> reading this topic gives me the sensation that there are more "cons" then
>>> "pros" when using an extended entity manager.
>>> 
>>> Besides avoiding Lazy initialization exceptions by letting the EM open in
>>> eg master detail views where else going stateful is really advantageous?
>>> 
>>> I've been working with stateless EM quite a lot and never needed an OSI
>>> filter, doing extra queries for fetching always did the trick.
>>> 
>>> 
>>> 
>>> 
>>> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
>>> 
>>>> Thanks, feels obvious now when you said it. Off topic but for my apps Marks
>>>> old suggestion on his blog to optionally drop pessimistic locking and make
>>>> it Serializable would be perfect for my apps.
>>>> 
>>>> 
>>>> 
>>>> 
>>>> 
>>>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>>>> 
>>>>> Karl,
>>>>> 
>>>>> Mostly because ConversationScope beans must be serializable and the EM is
>>>>> not (check the "transient" keyword on the variable that keeps in the
>>>>> ConversationScope Holder) and the fact that in our web apps, the EM can
>>>> be
>>>>> injected in components where the ConversationScope is not active (Namely
>>>>> MDBs and JAX-WS endpoints), where there is only one "request" and no need
>>>>> to get the same EM. For this we use another layer (Check my previous
>>>> posts
>>>>> about our the "EntityResolver" interface and implementations)
>>>>> 
>>>>> Denis
>>>>> 
>>>>> 
>>>>> Le 2015-04-19 14:33, Karl Kildén a écrit :
>>>>> 
>>>>>> Denis,
>>>>>> 
>>>>>> What's the added benefit of wrapping the em in @ConversationScoped
>>>> instead
>>>>>> of exposing it like this directly. I am also porting a huge seam app
>>>>>> (about
>>>>>> 1k views) so I do need extended em.
>>>>>> 
>>>>>> cheers
>>>>>> 
>>>>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>>>>>> 
>>>>>> 
>>>>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>>>>>> 
>>>>>>> Hi Dennis!
>>>>>>>> 
>>>>>>>> 
>>>>>>>> Have you *ever* hit this situation?
>>>>>>>> Yes, under heavy load it happens pretty often actually (I’m talking
>>>>>>>> about
>>>>>>>> multi-million request/day public internet apps). It also depends a bit
>>>>>>>> on
>>>>>>>> the JPA container you use. From the pure spec it is forbitten to touch
>>>>>>>> the
>>>>>>>> EntityManager in parallel threads and also to touch managed
>>>> (‚attached’)
>>>>>>>> entities in parallel threads. What JPA container are you using?
>>>>>>>> 
>>>>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
>>>>>>> So you have  applications with multi-million request/day concurrently
>>>> in
>>>>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>>>>>>> Impressive... How do you do that: Ajax requests? Proprietary client
>>>>>>> javascript framework?
>>>>>>> Or you are talking about *not closed EM* because the @PreDestroy
>>>> callback
>>>>>>> method has not been called in some particulat situation (sendRedirect
>>>> is
>>>>>>> called and the new request is processed before the initial request)?
>>>>>>> Sorry, Mark but you lost me.....
>>>>>>> Denis
>>>>>>> 
>>>>>>> 
>>>>>>> Also, who programs a „sendRedirect" in the middle of a method that
>>>> then
>>>>>>> 
>>>>>>>> performs database access ..?
>>>>>>>>> 
>>>>>>>>> You don’t need to do database access even. It is enough that the
>>>>>>>> entitymanager is not closed as per the spec.
>>>>>>>> 
>>>>>>>> 
>>>>>>>> Even so, this is pure theory, the chance are so tiny this happens…
>>>>>>>> Then I had bad luck - quite often ;)
>>>>>>>> 
>>>>>>>> 
>>>>>>>> And If you think this *may* happen within one conversation, then
>>>>>>>> change
>>>>>>>> 
>>>>>>>>> the way redirects are send, or the way database is accessed in
>>>>>>>>> parallel in
>>>>>>>>> Ajax requests. not the way EM is used IMHO
>>>>>>>>> 
>>>>>>>>> That might be a solution. Or force the EM to get closed before the
>>>>>>>> redirect.
>>>>>>>> 
>>>>>>>> Also your remark on „unfinished thread" is valid for ANY
>>>>>>>> 
>>>>>>>>> components/resources held in ConversationScope, not just the EM,
>>>> true?
>>>>>>>>> 
>>>>>>>>> Yes, but most components have no problems with getting accessed in
>>>>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
>>>>>>>> forbidden
>>>>>>>> by the JPA spec.
>>>>>>>> 
>>>>>>>> LieGrue,
>>>>>>>> strub
>>>>>>>> 
>>>>>>>> 
>>>>>>> 
>>>>> 
>>>> 
>>> 
>>> 
>>> 
>>> --
>>> <http://www.advancedit.com.br/>Att,
>>> 
>>> Rafael M. Pestano
>>> 
>>> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
>>> http://rpestano.wordpress.com/
>>> @realpestano <https://twitter.com/realpestano>
> 


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
You can do the same with DeltaSpike @Transactional and @TransactionScoped EntityManagers ;)

The difference is subtle but very important. Imo the EE7 javax.transaction.Transactional is as broken as EJB transactions if you build big real world apps (banks, insurance companies, government projects, etc). 
I really dislike the Exception handling in EJB and EE7 @Transactional. It’s soooo weird and most people are not aware how it works. I probably really should write up another blog post.

LieGrue,
strub

> Am 20.04.2015 um 17:14 schrieb Cody Lerum <co...@gmail.com>:
> 
> FWIW I started developing my application on Seam 2 with it's
> Conversation scoped EntityManager. Everything was so simple and
> everything worked, but my application was also very small at the time
> and everything was invoked by a user clicking a button or a link in a
> JSF page.
> 
> Over time my application grew to have JAX-WS and JAX-RS and timers. It
> also migrated from Seam to EE6/CDI. Since there are no Conversations
> during these types of requests this created issues and hacky
> workarounds. Eventually I converted to a RequestScoped EntityManager
> and everything was simple except for lazy loading and merging.
> 
> Over more time my application started to pick up some batch type
> processing requirements where I wanted to operate on multiple
> transactions within a single request which may be invoked from many
> different places.  I migrated to EE7 and converted to a EM per
> transaction. It is a bit more work to ensure that you merge and
> trigger lazy loads, but I feel that it gives me a lot of flexibility
> and removes a lot of limitations.
> 
> In my experience the extended EntityManagers can be a great time
> savings in initial app development, but they are also potential long
> term technical debt if your application keeps growing and introducing
> new requirements. I would just recommend that you really understand
> the context you are using (Session, Conversation, Request,
> Transaction) and know about when these contexts are and aren't created
> (and destroyed).
> 
> -C
> 
> On Sun, Apr 19, 2015 at 9:46 PM, Rafael Pestano <rm...@gmail.com> wrote:
>> reading this topic gives me the sensation that there are more "cons" then
>> "pros" when using an extended entity manager.
>> 
>> Besides avoiding Lazy initialization exceptions by letting the EM open in
>> eg master detail views where else going stateful is really advantageous?
>> 
>> I've been working with stateless EM quite a lot and never needed an OSI
>> filter, doing extra queries for fetching always did the trick.
>> 
>> 
>> 
>> 
>> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
>> 
>>> Thanks, feels obvious now when you said it. Off topic but for my apps Marks
>>> old suggestion on his blog to optionally drop pessimistic locking and make
>>> it Serializable would be perfect for my apps.
>>> 
>>> 
>>> 
>>> 
>>> 
>>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>>> 
>>>> Karl,
>>>> 
>>>> Mostly because ConversationScope beans must be serializable and the EM is
>>>> not (check the "transient" keyword on the variable that keeps in the
>>>> ConversationScope Holder) and the fact that in our web apps, the EM can
>>> be
>>>> injected in components where the ConversationScope is not active (Namely
>>>> MDBs and JAX-WS endpoints), where there is only one "request" and no need
>>>> to get the same EM. For this we use another layer (Check my previous
>>> posts
>>>> about our the "EntityResolver" interface and implementations)
>>>> 
>>>> Denis
>>>> 
>>>> 
>>>> Le 2015-04-19 14:33, Karl Kildén a écrit :
>>>> 
>>>>> Denis,
>>>>> 
>>>>> What's the added benefit of wrapping the em in @ConversationScoped
>>> instead
>>>>> of exposing it like this directly. I am also porting a huge seam app
>>>>> (about
>>>>> 1k views) so I do need extended em.
>>>>> 
>>>>> cheers
>>>>> 
>>>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>>>>> 
>>>>> 
>>>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>>>>> 
>>>>>> Hi Dennis!
>>>>>>> 
>>>>>>> 
>>>>>>>  Have you *ever* hit this situation?
>>>>>>> Yes, under heavy load it happens pretty often actually (I’m talking
>>>>>>> about
>>>>>>> multi-million request/day public internet apps). It also depends a bit
>>>>>>> on
>>>>>>> the JPA container you use. From the pure spec it is forbitten to touch
>>>>>>> the
>>>>>>> EntityManager in parallel threads and also to touch managed
>>> (‚attached’)
>>>>>>> entities in parallel threads. What JPA container are you using?
>>>>>>> 
>>>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
>>>>>> So you have  applications with multi-million request/day concurrently
>>> in
>>>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>>>>>> Impressive... How do you do that: Ajax requests? Proprietary client
>>>>>> javascript framework?
>>>>>> Or you are talking about *not closed EM* because the @PreDestroy
>>> callback
>>>>>> method has not been called in some particulat situation (sendRedirect
>>> is
>>>>>> called and the new request is processed before the initial request)?
>>>>>> Sorry, Mark but you lost me.....
>>>>>> Denis
>>>>>> 
>>>>>> 
>>>>>>  Also, who programs a „sendRedirect" in the middle of a method that
>>> then
>>>>>> 
>>>>>>> performs database access ..?
>>>>>>>> 
>>>>>>>> You don’t need to do database access even. It is enough that the
>>>>>>> entitymanager is not closed as per the spec.
>>>>>>> 
>>>>>>> 
>>>>>>>  Even so, this is pure theory, the chance are so tiny this happens…
>>>>>>> Then I had bad luck - quite often ;)
>>>>>>> 
>>>>>>> 
>>>>>>>  And If you think this *may* happen within one conversation, then
>>>>>>> change
>>>>>>> 
>>>>>>>> the way redirects are send, or the way database is accessed in
>>>>>>>> parallel in
>>>>>>>> Ajax requests. not the way EM is used IMHO
>>>>>>>> 
>>>>>>>> That might be a solution. Or force the EM to get closed before the
>>>>>>> redirect.
>>>>>>> 
>>>>>>>  Also your remark on „unfinished thread" is valid for ANY
>>>>>>> 
>>>>>>>> components/resources held in ConversationScope, not just the EM,
>>> true?
>>>>>>>> 
>>>>>>>> Yes, but most components have no problems with getting accessed in
>>>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
>>>>>>> forbidden
>>>>>>> by the JPA spec.
>>>>>>> 
>>>>>>> LieGrue,
>>>>>>> strub
>>>>>>> 
>>>>>>> 
>>>>>> 
>>>> 
>>> 
>> 
>> 
>> 
>> --
>> <http://www.advancedit.com.br/>Att,
>> 
>> Rafael M. Pestano
>> 
>> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
>> http://rpestano.wordpress.com/
>> @realpestano <https://twitter.com/realpestano>


Re: Extended EntityManager

Posted by Cody Lerum <co...@gmail.com>.
FWIW I started developing my application on Seam 2 with it's
Conversation scoped EntityManager. Everything was so simple and
everything worked, but my application was also very small at the time
and everything was invoked by a user clicking a button or a link in a
JSF page.

Over time my application grew to have JAX-WS and JAX-RS and timers. It
also migrated from Seam to EE6/CDI. Since there are no Conversations
during these types of requests this created issues and hacky
workarounds. Eventually I converted to a RequestScoped EntityManager
and everything was simple except for lazy loading and merging.

Over more time my application started to pick up some batch type
processing requirements where I wanted to operate on multiple
transactions within a single request which may be invoked from many
different places.  I migrated to EE7 and converted to a EM per
transaction. It is a bit more work to ensure that you merge and
trigger lazy loads, but I feel that it gives me a lot of flexibility
and removes a lot of limitations.

In my experience the extended EntityManagers can be a great time
savings in initial app development, but they are also potential long
term technical debt if your application keeps growing and introducing
new requirements. I would just recommend that you really understand
the context you are using (Session, Conversation, Request,
Transaction) and know about when these contexts are and aren't created
(and destroyed).

-C

On Sun, Apr 19, 2015 at 9:46 PM, Rafael Pestano <rm...@gmail.com> wrote:
> reading this topic gives me the sensation that there are more "cons" then
> "pros" when using an extended entity manager.
>
> Besides avoiding Lazy initialization exceptions by letting the EM open in
> eg master detail views where else going stateful is really advantageous?
>
> I've been working with stateless EM quite a lot and never needed an OSI
> filter, doing extra queries for fetching always did the trick.
>
>
>
>
> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
>
>> Thanks, feels obvious now when you said it. Off topic but for my apps Marks
>> old suggestion on his blog to optionally drop pessimistic locking and make
>> it Serializable would be perfect for my apps.
>>
>>
>>
>>
>>
>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>>
>> > Karl,
>> >
>> > Mostly because ConversationScope beans must be serializable and the EM is
>> > not (check the "transient" keyword on the variable that keeps in the
>> > ConversationScope Holder) and the fact that in our web apps, the EM can
>> be
>> > injected in components where the ConversationScope is not active (Namely
>> > MDBs and JAX-WS endpoints), where there is only one "request" and no need
>> > to get the same EM. For this we use another layer (Check my previous
>> posts
>> > about our the "EntityResolver" interface and implementations)
>> >
>> > Denis
>> >
>> >
>> > Le 2015-04-19 14:33, Karl Kildén a écrit :
>> >
>> >> Denis,
>> >>
>> >> What's the added benefit of wrapping the em in @ConversationScoped
>> instead
>> >> of exposing it like this directly. I am also porting a huge seam app
>> >> (about
>> >> 1k views) so I do need extended em.
>> >>
>> >> cheers
>> >>
>> >> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>> >>
>> >>
>> >>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>> >>>
>> >>>  Hi Dennis!
>> >>>>
>> >>>>
>> >>>>   Have you *ever* hit this situation?
>> >>>> Yes, under heavy load it happens pretty often actually (I’m talking
>> >>>> about
>> >>>> multi-million request/day public internet apps). It also depends a bit
>> >>>> on
>> >>>> the JPA container you use. From the pure spec it is forbitten to touch
>> >>>> the
>> >>>> EntityManager in parallel threads and also to touch managed
>> (‚attached’)
>> >>>> entities in parallel threads. What JPA container are you using?
>> >>>>
>> >>>>  Here we are talking about one ONE EM per ONE CDI Conversation.
>> >>> So you have  applications with multi-million request/day concurrently
>> in
>> >>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>> >>> Impressive... How do you do that: Ajax requests? Proprietary client
>> >>> javascript framework?
>> >>> Or you are talking about *not closed EM* because the @PreDestroy
>> callback
>> >>> method has not been called in some particulat situation (sendRedirect
>> is
>> >>> called and the new request is processed before the initial request)?
>> >>> Sorry, Mark but you lost me.....
>> >>> Denis
>> >>>
>> >>>
>> >>>   Also, who programs a „sendRedirect" in the middle of a method that
>> then
>> >>>
>> >>>> performs database access ..?
>> >>>>>
>> >>>>>  You don’t need to do database access even. It is enough that the
>> >>>> entitymanager is not closed as per the spec.
>> >>>>
>> >>>>
>> >>>>   Even so, this is pure theory, the chance are so tiny this happens…
>> >>>> Then I had bad luck - quite often ;)
>> >>>>
>> >>>>
>> >>>>   And If you think this *may* happen within one conversation, then
>> >>>> change
>> >>>>
>> >>>>> the way redirects are send, or the way database is accessed in
>> >>>>> parallel in
>> >>>>> Ajax requests. not the way EM is used IMHO
>> >>>>>
>> >>>>>  That might be a solution. Or force the EM to get closed before the
>> >>>> redirect.
>> >>>>
>> >>>>   Also your remark on „unfinished thread" is valid for ANY
>> >>>>
>> >>>>> components/resources held in ConversationScope, not just the EM,
>> true?
>> >>>>>
>> >>>>>  Yes, but most components have no problems with getting accessed in
>> >>>> parallel. For managed Entities and EntityManagers it’s explicitly
>> >>>> forbidden
>> >>>> by the JPA spec.
>> >>>>
>> >>>> LieGrue,
>> >>>> strub
>> >>>>
>> >>>>
>> >>>
>> >
>>
>
>
>
> --
> <http://www.advancedit.com.br/>Att,
>
> Rafael M. Pestano
>
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
Hi Gerhard,

yea, thats what i said "UserService uses a transaction entity manager"

so that's my point, on that example although the entity is detached we
don't need DTOs right? we just have "more work" to reatach it...anyway @Cody
Lerum <https://plus.google.com/u/0/102516208312961178993?prsrc=4> gave us a
great explanation/report

thanks for the great discussion.

2015-04-20 12:27 GMT-03:00 Gerhard Petracek <gp...@apache.org>:

> hi rafael,
>
> in that example you don't have an extended entity-manager and therefore the
> returned entity is detached.
> (as you can see in UserRepository the entity gets merged later on... -
> that's what mark mentioned in his first explanation as well.)
>
> regards,
> gerhard
>
>
>
> 2015-04-20 17:05 GMT+02:00 Rafael Pestano <rm...@gmail.com>:
>
> > Hi Mark,
> >
> > we don't use DTOs, our JSF forms(backed by ViewAccessScoped beans) use
> JPA
> > entities and we usually load dependent entities on preRenderView event or
> > on demand (click on button, fetch relationships and go to detail page)
> >
> > Do you have a sample where DTO is needed when using a stateless entity
> > manager?
> >
> > eg: at [1] UserService uses a transaction entity manager and the JPA
> entity
> > (User) is expoded direcly in the JSF form. But of course in this example
> > user is a simple entity but if it were a complex one I think it would not
> > be necessary to have a User DTO.
> >
> >
> >
> > [1]
> >
> >
> https://github.com/os890/ee6-ds-demo/blob/master/src/main/java/org/os890/demo/ee6/ds/view/controller/user/RegistrationPage.java
> >
> >
> > 2015-04-20 11:44 GMT-03:00 Mark Struberg <st...@yahoo.de>:
> >
> > > If your app doesn’t store entities in JSF backing beans but use DTOs
> then
> > > all is fine.
> > > But does your DTOs contain the @Version field of your entity? Do you
> > > manually check if the version is still unchanged on the re-apply?
> > > Most of the applications working with DTOs did _not_ do that and are
> > utter
> > > broken because they overwrite state in the db without any locking…
> > >
> > > LieGrue,
> > > strub
> > >
> > >
> > > > Am 20.04.2015 um 03:46 schrieb Rafael Pestano <rm...@gmail.com>:
> > > >
> > > > reading this topic gives me the sensation that there are more "cons"
> > then
> > > > "pros" when using an extended entity manager.
> > > >
> > > > Besides avoiding Lazy initialization exceptions by letting the EM
> open
> > in
> > > > eg master detail views where else going stateful is really
> > advantageous?
> > > >
> > > > I've been working with stateless EM quite a lot and never needed an
> OSI
> > > > filter, doing extra queries for fetching always did the trick.
> > > >
> > > >
> > > >
> > > >
> > > > 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> > > >
> > > >> Thanks, feels obvious now when you said it. Off topic but for my
> apps
> > > Marks
> > > >> old suggestion on his blog to optionally drop pessimistic locking
> and
> > > make
> > > >> it Serializable would be perfect for my apps.
> > > >>
> > > >>
> > > >>
> > > >>
> > > >>
> > > >> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com>
> wrote:
> > > >>
> > > >>> Karl,
> > > >>>
> > > >>> Mostly because ConversationScope beans must be serializable and the
> > EM
> > > is
> > > >>> not (check the "transient" keyword on the variable that keeps in
> the
> > > >>> ConversationScope Holder) and the fact that in our web apps, the EM
> > can
> > > >> be
> > > >>> injected in components where the ConversationScope is not active
> > > (Namely
> > > >>> MDBs and JAX-WS endpoints), where there is only one "request" and
> no
> > > need
> > > >>> to get the same EM. For this we use another layer (Check my
> previous
> > > >> posts
> > > >>> about our the "EntityResolver" interface and implementations)
> > > >>>
> > > >>> Denis
> > > >>>
> > > >>>
> > > >>> Le 2015-04-19 14:33, Karl Kildén a écrit :
> > > >>>
> > > >>>> Denis,
> > > >>>>
> > > >>>> What's the added benefit of wrapping the em in @ConversationScoped
> > > >> instead
> > > >>>> of exposing it like this directly. I am also porting a huge seam
> app
> > > >>>> (about
> > > >>>> 1k views) so I do need extended em.
> > > >>>>
> > > >>>> cheers
> > > >>>>
> > > >>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com>
> > wrote:
> > > >>>>
> > > >>>>
> > > >>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
> > > >>>>>
> > > >>>>> Hi Dennis!
> > > >>>>>>
> > > >>>>>>
> > > >>>>>>  Have you *ever* hit this situation?
> > > >>>>>> Yes, under heavy load it happens pretty often actually (I’m
> > talking
> > > >>>>>> about
> > > >>>>>> multi-million request/day public internet apps). It also
> depends a
> > > bit
> > > >>>>>> on
> > > >>>>>> the JPA container you use. From the pure spec it is forbitten to
> > > touch
> > > >>>>>> the
> > > >>>>>> EntityManager in parallel threads and also to touch managed
> > > >> (‚attached’)
> > > >>>>>> entities in parallel threads. What JPA container are you using?
> > > >>>>>>
> > > >>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
> > > >>>>> So you have  applications with multi-million request/day
> > concurrently
> > > >> in
> > > >>>>> one CDI Conversation that may lead *often* to a misuse of the EM
> ?
> > > >>>>> Impressive... How do you do that: Ajax requests? Proprietary
> client
> > > >>>>> javascript framework?
> > > >>>>> Or you are talking about *not closed EM* because the @PreDestroy
> > > >> callback
> > > >>>>> method has not been called in some particulat situation
> > (sendRedirect
> > > >> is
> > > >>>>> called and the new request is processed before the initial
> > request)?
> > > >>>>> Sorry, Mark but you lost me.....
> > > >>>>> Denis
> > > >>>>>
> > > >>>>>
> > > >>>>>  Also, who programs a „sendRedirect" in the middle of a method
> that
> > > >> then
> > > >>>>>
> > > >>>>>> performs database access ..?
> > > >>>>>>>
> > > >>>>>>> You don’t need to do database access even. It is enough that
> the
> > > >>>>>> entitymanager is not closed as per the spec.
> > > >>>>>>
> > > >>>>>>
> > > >>>>>>  Even so, this is pure theory, the chance are so tiny this
> > happens…
> > > >>>>>> Then I had bad luck - quite often ;)
> > > >>>>>>
> > > >>>>>>
> > > >>>>>>  And If you think this *may* happen within one conversation,
> then
> > > >>>>>> change
> > > >>>>>>
> > > >>>>>>> the way redirects are send, or the way database is accessed in
> > > >>>>>>> parallel in
> > > >>>>>>> Ajax requests. not the way EM is used IMHO
> > > >>>>>>>
> > > >>>>>>> That might be a solution. Or force the EM to get closed before
> > the
> > > >>>>>> redirect.
> > > >>>>>>
> > > >>>>>>  Also your remark on „unfinished thread" is valid for ANY
> > > >>>>>>
> > > >>>>>>> components/resources held in ConversationScope, not just the
> EM,
> > > >> true?
> > > >>>>>>>
> > > >>>>>>> Yes, but most components have no problems with getting accessed
> > in
> > > >>>>>> parallel. For managed Entities and EntityManagers it’s
> explicitly
> > > >>>>>> forbidden
> > > >>>>>> by the JPA spec.
> > > >>>>>>
> > > >>>>>> LieGrue,
> > > >>>>>> strub
> > > >>>>>>
> > > >>>>>>
> > > >>>>>
> > > >>>
> > > >>
> > > >
> > > >
> > > >
> > > > --
> > > > <http://www.advancedit.com.br/>Att,
> > > >
> > > > Rafael M. Pestano
> > > >
> > > > Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do
> Sul
> > > > http://rpestano.wordpress.com/
> > > > @realpestano <https://twitter.com/realpestano>
> > >
> > >
> >
> >
> > --
> > <http://www.advancedit.com.br/>Att,
> >
> > Rafael M. Pestano
> >
> > Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> > http://rpestano.wordpress.com/
> > @realpestano <https://twitter.com/realpestano>
> >
>



-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Gerhard Petracek <gp...@apache.org>.
hi rafael,

in that example you don't have an extended entity-manager and therefore the
returned entity is detached.
(as you can see in UserRepository the entity gets merged later on... -
that's what mark mentioned in his first explanation as well.)

regards,
gerhard



2015-04-20 17:05 GMT+02:00 Rafael Pestano <rm...@gmail.com>:

> Hi Mark,
>
> we don't use DTOs, our JSF forms(backed by ViewAccessScoped beans) use JPA
> entities and we usually load dependent entities on preRenderView event or
> on demand (click on button, fetch relationships and go to detail page)
>
> Do you have a sample where DTO is needed when using a stateless entity
> manager?
>
> eg: at [1] UserService uses a transaction entity manager and the JPA entity
> (User) is expoded direcly in the JSF form. But of course in this example
> user is a simple entity but if it were a complex one I think it would not
> be necessary to have a User DTO.
>
>
>
> [1]
>
> https://github.com/os890/ee6-ds-demo/blob/master/src/main/java/org/os890/demo/ee6/ds/view/controller/user/RegistrationPage.java
>
>
> 2015-04-20 11:44 GMT-03:00 Mark Struberg <st...@yahoo.de>:
>
> > If your app doesn’t store entities in JSF backing beans but use DTOs then
> > all is fine.
> > But does your DTOs contain the @Version field of your entity? Do you
> > manually check if the version is still unchanged on the re-apply?
> > Most of the applications working with DTOs did _not_ do that and are
> utter
> > broken because they overwrite state in the db without any locking…
> >
> > LieGrue,
> > strub
> >
> >
> > > Am 20.04.2015 um 03:46 schrieb Rafael Pestano <rm...@gmail.com>:
> > >
> > > reading this topic gives me the sensation that there are more "cons"
> then
> > > "pros" when using an extended entity manager.
> > >
> > > Besides avoiding Lazy initialization exceptions by letting the EM open
> in
> > > eg master detail views where else going stateful is really
> advantageous?
> > >
> > > I've been working with stateless EM quite a lot and never needed an OSI
> > > filter, doing extra queries for fetching always did the trick.
> > >
> > >
> > >
> > >
> > > 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> > >
> > >> Thanks, feels obvious now when you said it. Off topic but for my apps
> > Marks
> > >> old suggestion on his blog to optionally drop pessimistic locking and
> > make
> > >> it Serializable would be perfect for my apps.
> > >>
> > >>
> > >>
> > >>
> > >>
> > >> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
> > >>
> > >>> Karl,
> > >>>
> > >>> Mostly because ConversationScope beans must be serializable and the
> EM
> > is
> > >>> not (check the "transient" keyword on the variable that keeps in the
> > >>> ConversationScope Holder) and the fact that in our web apps, the EM
> can
> > >> be
> > >>> injected in components where the ConversationScope is not active
> > (Namely
> > >>> MDBs and JAX-WS endpoints), where there is only one "request" and no
> > need
> > >>> to get the same EM. For this we use another layer (Check my previous
> > >> posts
> > >>> about our the "EntityResolver" interface and implementations)
> > >>>
> > >>> Denis
> > >>>
> > >>>
> > >>> Le 2015-04-19 14:33, Karl Kildén a écrit :
> > >>>
> > >>>> Denis,
> > >>>>
> > >>>> What's the added benefit of wrapping the em in @ConversationScoped
> > >> instead
> > >>>> of exposing it like this directly. I am also porting a huge seam app
> > >>>> (about
> > >>>> 1k views) so I do need extended em.
> > >>>>
> > >>>> cheers
> > >>>>
> > >>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com>
> wrote:
> > >>>>
> > >>>>
> > >>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
> > >>>>>
> > >>>>> Hi Dennis!
> > >>>>>>
> > >>>>>>
> > >>>>>>  Have you *ever* hit this situation?
> > >>>>>> Yes, under heavy load it happens pretty often actually (I’m
> talking
> > >>>>>> about
> > >>>>>> multi-million request/day public internet apps). It also depends a
> > bit
> > >>>>>> on
> > >>>>>> the JPA container you use. From the pure spec it is forbitten to
> > touch
> > >>>>>> the
> > >>>>>> EntityManager in parallel threads and also to touch managed
> > >> (‚attached’)
> > >>>>>> entities in parallel threads. What JPA container are you using?
> > >>>>>>
> > >>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
> > >>>>> So you have  applications with multi-million request/day
> concurrently
> > >> in
> > >>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
> > >>>>> Impressive... How do you do that: Ajax requests? Proprietary client
> > >>>>> javascript framework?
> > >>>>> Or you are talking about *not closed EM* because the @PreDestroy
> > >> callback
> > >>>>> method has not been called in some particulat situation
> (sendRedirect
> > >> is
> > >>>>> called and the new request is processed before the initial
> request)?
> > >>>>> Sorry, Mark but you lost me.....
> > >>>>> Denis
> > >>>>>
> > >>>>>
> > >>>>>  Also, who programs a „sendRedirect" in the middle of a method that
> > >> then
> > >>>>>
> > >>>>>> performs database access ..?
> > >>>>>>>
> > >>>>>>> You don’t need to do database access even. It is enough that the
> > >>>>>> entitymanager is not closed as per the spec.
> > >>>>>>
> > >>>>>>
> > >>>>>>  Even so, this is pure theory, the chance are so tiny this
> happens…
> > >>>>>> Then I had bad luck - quite often ;)
> > >>>>>>
> > >>>>>>
> > >>>>>>  And If you think this *may* happen within one conversation, then
> > >>>>>> change
> > >>>>>>
> > >>>>>>> the way redirects are send, or the way database is accessed in
> > >>>>>>> parallel in
> > >>>>>>> Ajax requests. not the way EM is used IMHO
> > >>>>>>>
> > >>>>>>> That might be a solution. Or force the EM to get closed before
> the
> > >>>>>> redirect.
> > >>>>>>
> > >>>>>>  Also your remark on „unfinished thread" is valid for ANY
> > >>>>>>
> > >>>>>>> components/resources held in ConversationScope, not just the EM,
> > >> true?
> > >>>>>>>
> > >>>>>>> Yes, but most components have no problems with getting accessed
> in
> > >>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
> > >>>>>> forbidden
> > >>>>>> by the JPA spec.
> > >>>>>>
> > >>>>>> LieGrue,
> > >>>>>> strub
> > >>>>>>
> > >>>>>>
> > >>>>>
> > >>>
> > >>
> > >
> > >
> > >
> > > --
> > > <http://www.advancedit.com.br/>Att,
> > >
> > > Rafael M. Pestano
> > >
> > > Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> > > http://rpestano.wordpress.com/
> > > @realpestano <https://twitter.com/realpestano>
> >
> >
>
>
> --
> <http://www.advancedit.com.br/>Att,
>
> Rafael M. Pestano
>
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>
>

Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
Hi Mark,

we don't use DTOs, our JSF forms(backed by ViewAccessScoped beans) use JPA
entities and we usually load dependent entities on preRenderView event or
on demand (click on button, fetch relationships and go to detail page)

Do you have a sample where DTO is needed when using a stateless entity
manager?

eg: at [1] UserService uses a transaction entity manager and the JPA entity
(User) is expoded direcly in the JSF form. But of course in this example
user is a simple entity but if it were a complex one I think it would not
be necessary to have a User DTO.



[1]
https://github.com/os890/ee6-ds-demo/blob/master/src/main/java/org/os890/demo/ee6/ds/view/controller/user/RegistrationPage.java


2015-04-20 11:44 GMT-03:00 Mark Struberg <st...@yahoo.de>:

> If your app doesn’t store entities in JSF backing beans but use DTOs then
> all is fine.
> But does your DTOs contain the @Version field of your entity? Do you
> manually check if the version is still unchanged on the re-apply?
> Most of the applications working with DTOs did _not_ do that and are utter
> broken because they overwrite state in the db without any locking…
>
> LieGrue,
> strub
>
>
> > Am 20.04.2015 um 03:46 schrieb Rafael Pestano <rm...@gmail.com>:
> >
> > reading this topic gives me the sensation that there are more "cons" then
> > "pros" when using an extended entity manager.
> >
> > Besides avoiding Lazy initialization exceptions by letting the EM open in
> > eg master detail views where else going stateful is really advantageous?
> >
> > I've been working with stateless EM quite a lot and never needed an OSI
> > filter, doing extra queries for fetching always did the trick.
> >
> >
> >
> >
> > 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> >
> >> Thanks, feels obvious now when you said it. Off topic but for my apps
> Marks
> >> old suggestion on his blog to optionally drop pessimistic locking and
> make
> >> it Serializable would be perfect for my apps.
> >>
> >>
> >>
> >>
> >>
> >> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
> >>
> >>> Karl,
> >>>
> >>> Mostly because ConversationScope beans must be serializable and the EM
> is
> >>> not (check the "transient" keyword on the variable that keeps in the
> >>> ConversationScope Holder) and the fact that in our web apps, the EM can
> >> be
> >>> injected in components where the ConversationScope is not active
> (Namely
> >>> MDBs and JAX-WS endpoints), where there is only one "request" and no
> need
> >>> to get the same EM. For this we use another layer (Check my previous
> >> posts
> >>> about our the "EntityResolver" interface and implementations)
> >>>
> >>> Denis
> >>>
> >>>
> >>> Le 2015-04-19 14:33, Karl Kildén a écrit :
> >>>
> >>>> Denis,
> >>>>
> >>>> What's the added benefit of wrapping the em in @ConversationScoped
> >> instead
> >>>> of exposing it like this directly. I am also porting a huge seam app
> >>>> (about
> >>>> 1k views) so I do need extended em.
> >>>>
> >>>> cheers
> >>>>
> >>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
> >>>>
> >>>>
> >>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
> >>>>>
> >>>>> Hi Dennis!
> >>>>>>
> >>>>>>
> >>>>>>  Have you *ever* hit this situation?
> >>>>>> Yes, under heavy load it happens pretty often actually (I’m talking
> >>>>>> about
> >>>>>> multi-million request/day public internet apps). It also depends a
> bit
> >>>>>> on
> >>>>>> the JPA container you use. From the pure spec it is forbitten to
> touch
> >>>>>> the
> >>>>>> EntityManager in parallel threads and also to touch managed
> >> (‚attached’)
> >>>>>> entities in parallel threads. What JPA container are you using?
> >>>>>>
> >>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
> >>>>> So you have  applications with multi-million request/day concurrently
> >> in
> >>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
> >>>>> Impressive... How do you do that: Ajax requests? Proprietary client
> >>>>> javascript framework?
> >>>>> Or you are talking about *not closed EM* because the @PreDestroy
> >> callback
> >>>>> method has not been called in some particulat situation (sendRedirect
> >> is
> >>>>> called and the new request is processed before the initial request)?
> >>>>> Sorry, Mark but you lost me.....
> >>>>> Denis
> >>>>>
> >>>>>
> >>>>>  Also, who programs a „sendRedirect" in the middle of a method that
> >> then
> >>>>>
> >>>>>> performs database access ..?
> >>>>>>>
> >>>>>>> You don’t need to do database access even. It is enough that the
> >>>>>> entitymanager is not closed as per the spec.
> >>>>>>
> >>>>>>
> >>>>>>  Even so, this is pure theory, the chance are so tiny this happens…
> >>>>>> Then I had bad luck - quite often ;)
> >>>>>>
> >>>>>>
> >>>>>>  And If you think this *may* happen within one conversation, then
> >>>>>> change
> >>>>>>
> >>>>>>> the way redirects are send, or the way database is accessed in
> >>>>>>> parallel in
> >>>>>>> Ajax requests. not the way EM is used IMHO
> >>>>>>>
> >>>>>>> That might be a solution. Or force the EM to get closed before the
> >>>>>> redirect.
> >>>>>>
> >>>>>>  Also your remark on „unfinished thread" is valid for ANY
> >>>>>>
> >>>>>>> components/resources held in ConversationScope, not just the EM,
> >> true?
> >>>>>>>
> >>>>>>> Yes, but most components have no problems with getting accessed in
> >>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
> >>>>>> forbidden
> >>>>>> by the JPA spec.
> >>>>>>
> >>>>>> LieGrue,
> >>>>>> strub
> >>>>>>
> >>>>>>
> >>>>>
> >>>
> >>
> >
> >
> >
> > --
> > <http://www.advancedit.com.br/>Att,
> >
> > Rafael M. Pestano
> >
> > Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> > http://rpestano.wordpress.com/
> > @realpestano <https://twitter.com/realpestano>
>
>


-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
If your app doesn’t store entities in JSF backing beans but use DTOs then all is fine. 
But does your DTOs contain the @Version field of your entity? Do you manually check if the version is still unchanged on the re-apply?
Most of the applications working with DTOs did _not_ do that and are utter broken because they overwrite state in the db without any locking…

LieGrue,
strub


> Am 20.04.2015 um 03:46 schrieb Rafael Pestano <rm...@gmail.com>:
> 
> reading this topic gives me the sensation that there are more "cons" then
> "pros" when using an extended entity manager.
> 
> Besides avoiding Lazy initialization exceptions by letting the EM open in
> eg master detail views where else going stateful is really advantageous?
> 
> I've been working with stateless EM quite a lot and never needed an OSI
> filter, doing extra queries for fetching always did the trick.
> 
> 
> 
> 
> 2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:
> 
>> Thanks, feels obvious now when you said it. Off topic but for my apps Marks
>> old suggestion on his blog to optionally drop pessimistic locking and make
>> it Serializable would be perfect for my apps.
>> 
>> 
>> 
>> 
>> 
>> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>> 
>>> Karl,
>>> 
>>> Mostly because ConversationScope beans must be serializable and the EM is
>>> not (check the "transient" keyword on the variable that keeps in the
>>> ConversationScope Holder) and the fact that in our web apps, the EM can
>> be
>>> injected in components where the ConversationScope is not active (Namely
>>> MDBs and JAX-WS endpoints), where there is only one "request" and no need
>>> to get the same EM. For this we use another layer (Check my previous
>> posts
>>> about our the "EntityResolver" interface and implementations)
>>> 
>>> Denis
>>> 
>>> 
>>> Le 2015-04-19 14:33, Karl Kildén a écrit :
>>> 
>>>> Denis,
>>>> 
>>>> What's the added benefit of wrapping the em in @ConversationScoped
>> instead
>>>> of exposing it like this directly. I am also porting a huge seam app
>>>> (about
>>>> 1k views) so I do need extended em.
>>>> 
>>>> cheers
>>>> 
>>>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>>>> 
>>>> 
>>>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>>>> 
>>>>> Hi Dennis!
>>>>>> 
>>>>>> 
>>>>>>  Have you *ever* hit this situation?
>>>>>> Yes, under heavy load it happens pretty often actually (I’m talking
>>>>>> about
>>>>>> multi-million request/day public internet apps). It also depends a bit
>>>>>> on
>>>>>> the JPA container you use. From the pure spec it is forbitten to touch
>>>>>> the
>>>>>> EntityManager in parallel threads and also to touch managed
>> (‚attached’)
>>>>>> entities in parallel threads. What JPA container are you using?
>>>>>> 
>>>>>> Here we are talking about one ONE EM per ONE CDI Conversation.
>>>>> So you have  applications with multi-million request/day concurrently
>> in
>>>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>>>>> Impressive... How do you do that: Ajax requests? Proprietary client
>>>>> javascript framework?
>>>>> Or you are talking about *not closed EM* because the @PreDestroy
>> callback
>>>>> method has not been called in some particulat situation (sendRedirect
>> is
>>>>> called and the new request is processed before the initial request)?
>>>>> Sorry, Mark but you lost me.....
>>>>> Denis
>>>>> 
>>>>> 
>>>>>  Also, who programs a „sendRedirect" in the middle of a method that
>> then
>>>>> 
>>>>>> performs database access ..?
>>>>>>> 
>>>>>>> You don’t need to do database access even. It is enough that the
>>>>>> entitymanager is not closed as per the spec.
>>>>>> 
>>>>>> 
>>>>>>  Even so, this is pure theory, the chance are so tiny this happens…
>>>>>> Then I had bad luck - quite often ;)
>>>>>> 
>>>>>> 
>>>>>>  And If you think this *may* happen within one conversation, then
>>>>>> change
>>>>>> 
>>>>>>> the way redirects are send, or the way database is accessed in
>>>>>>> parallel in
>>>>>>> Ajax requests. not the way EM is used IMHO
>>>>>>> 
>>>>>>> That might be a solution. Or force the EM to get closed before the
>>>>>> redirect.
>>>>>> 
>>>>>>  Also your remark on „unfinished thread" is valid for ANY
>>>>>> 
>>>>>>> components/resources held in ConversationScope, not just the EM,
>> true?
>>>>>>> 
>>>>>>> Yes, but most components have no problems with getting accessed in
>>>>>> parallel. For managed Entities and EntityManagers it’s explicitly
>>>>>> forbidden
>>>>>> by the JPA spec.
>>>>>> 
>>>>>> LieGrue,
>>>>>> strub
>>>>>> 
>>>>>> 
>>>>> 
>>> 
>> 
> 
> 
> 
> -- 
> <http://www.advancedit.com.br/>Att,
> 
> Rafael M. Pestano
> 
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>


Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
reading this topic gives me the sensation that there are more "cons" then
"pros" when using an extended entity manager.

Besides avoiding Lazy initialization exceptions by letting the EM open in
eg master detail views where else going stateful is really advantageous?

I've been working with stateless EM quite a lot and never needed an OSI
filter, doing extra queries for fetching always did the trick.




2015-04-19 18:19 GMT-03:00 Karl Kildén <ka...@gmail.com>:

> Thanks, feels obvious now when you said it. Off topic but for my apps Marks
> old suggestion on his blog to optionally drop pessimistic locking and make
> it Serializable would be perfect for my apps.
>
>
>
>
>
> On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:
>
> > Karl,
> >
> > Mostly because ConversationScope beans must be serializable and the EM is
> > not (check the "transient" keyword on the variable that keeps in the
> > ConversationScope Holder) and the fact that in our web apps, the EM can
> be
> > injected in components where the ConversationScope is not active (Namely
> > MDBs and JAX-WS endpoints), where there is only one "request" and no need
> > to get the same EM. For this we use another layer (Check my previous
> posts
> > about our the "EntityResolver" interface and implementations)
> >
> > Denis
> >
> >
> > Le 2015-04-19 14:33, Karl Kildén a écrit :
> >
> >> Denis,
> >>
> >> What's the added benefit of wrapping the em in @ConversationScoped
> instead
> >> of exposing it like this directly. I am also porting a huge seam app
> >> (about
> >> 1k views) so I do need extended em.
> >>
> >> cheers
> >>
> >> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
> >>
> >>
> >>> Le 2015-04-19 11:24, Mark Struberg a écrit :
> >>>
> >>>  Hi Dennis!
> >>>>
> >>>>
> >>>>   Have you *ever* hit this situation?
> >>>> Yes, under heavy load it happens pretty often actually (I’m talking
> >>>> about
> >>>> multi-million request/day public internet apps). It also depends a bit
> >>>> on
> >>>> the JPA container you use. From the pure spec it is forbitten to touch
> >>>> the
> >>>> EntityManager in parallel threads and also to touch managed
> (‚attached’)
> >>>> entities in parallel threads. What JPA container are you using?
> >>>>
> >>>>  Here we are talking about one ONE EM per ONE CDI Conversation.
> >>> So you have  applications with multi-million request/day concurrently
> in
> >>> one CDI Conversation that may lead *often* to a misuse of the EM ?
> >>> Impressive... How do you do that: Ajax requests? Proprietary client
> >>> javascript framework?
> >>> Or you are talking about *not closed EM* because the @PreDestroy
> callback
> >>> method has not been called in some particulat situation (sendRedirect
> is
> >>> called and the new request is processed before the initial request)?
> >>> Sorry, Mark but you lost me.....
> >>> Denis
> >>>
> >>>
> >>>   Also, who programs a „sendRedirect" in the middle of a method that
> then
> >>>
> >>>> performs database access ..?
> >>>>>
> >>>>>  You don’t need to do database access even. It is enough that the
> >>>> entitymanager is not closed as per the spec.
> >>>>
> >>>>
> >>>>   Even so, this is pure theory, the chance are so tiny this happens…
> >>>> Then I had bad luck - quite often ;)
> >>>>
> >>>>
> >>>>   And If you think this *may* happen within one conversation, then
> >>>> change
> >>>>
> >>>>> the way redirects are send, or the way database is accessed in
> >>>>> parallel in
> >>>>> Ajax requests. not the way EM is used IMHO
> >>>>>
> >>>>>  That might be a solution. Or force the EM to get closed before the
> >>>> redirect.
> >>>>
> >>>>   Also your remark on „unfinished thread" is valid for ANY
> >>>>
> >>>>> components/resources held in ConversationScope, not just the EM,
> true?
> >>>>>
> >>>>>  Yes, but most components have no problems with getting accessed in
> >>>> parallel. For managed Entities and EntityManagers it’s explicitly
> >>>> forbidden
> >>>> by the JPA spec.
> >>>>
> >>>> LieGrue,
> >>>> strub
> >>>>
> >>>>
> >>>
> >
>



-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by Karl Kildén <ka...@gmail.com>.
Thanks, feels obvious now when you said it. Off topic but for my apps Marks
old suggestion on his blog to optionally drop pessimistic locking and make
it Serializable would be perfect for my apps.





On 19 April 2015 at 21:28, titou10 <ti...@gmail.com> wrote:

> Karl,
>
> Mostly because ConversationScope beans must be serializable and the EM is
> not (check the "transient" keyword on the variable that keeps in the
> ConversationScope Holder) and the fact that in our web apps, the EM can be
> injected in components where the ConversationScope is not active (Namely
> MDBs and JAX-WS endpoints), where there is only one "request" and no need
> to get the same EM. For this we use another layer (Check my previous posts
> about our the "EntityResolver" interface and implementations)
>
> Denis
>
>
> Le 2015-04-19 14:33, Karl Kildén a écrit :
>
>> Denis,
>>
>> What's the added benefit of wrapping the em in @ConversationScoped instead
>> of exposing it like this directly. I am also porting a huge seam app
>> (about
>> 1k views) so I do need extended em.
>>
>> cheers
>>
>> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>>
>>
>>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>>
>>>  Hi Dennis!
>>>>
>>>>
>>>>   Have you *ever* hit this situation?
>>>> Yes, under heavy load it happens pretty often actually (I’m talking
>>>> about
>>>> multi-million request/day public internet apps). It also depends a bit
>>>> on
>>>> the JPA container you use. From the pure spec it is forbitten to touch
>>>> the
>>>> EntityManager in parallel threads and also to touch managed (‚attached’)
>>>> entities in parallel threads. What JPA container are you using?
>>>>
>>>>  Here we are talking about one ONE EM per ONE CDI Conversation.
>>> So you have  applications with multi-million request/day concurrently in
>>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>>> Impressive... How do you do that: Ajax requests? Proprietary client
>>> javascript framework?
>>> Or you are talking about *not closed EM* because the @PreDestroy callback
>>> method has not been called in some particulat situation (sendRedirect is
>>> called and the new request is processed before the initial request)?
>>> Sorry, Mark but you lost me.....
>>> Denis
>>>
>>>
>>>   Also, who programs a „sendRedirect" in the middle of a method that then
>>>
>>>> performs database access ..?
>>>>>
>>>>>  You don’t need to do database access even. It is enough that the
>>>> entitymanager is not closed as per the spec.
>>>>
>>>>
>>>>   Even so, this is pure theory, the chance are so tiny this happens…
>>>> Then I had bad luck - quite often ;)
>>>>
>>>>
>>>>   And If you think this *may* happen within one conversation, then
>>>> change
>>>>
>>>>> the way redirects are send, or the way database is accessed in
>>>>> parallel in
>>>>> Ajax requests. not the way EM is used IMHO
>>>>>
>>>>>  That might be a solution. Or force the EM to get closed before the
>>>> redirect.
>>>>
>>>>   Also your remark on „unfinished thread" is valid for ANY
>>>>
>>>>> components/resources held in ConversationScope, not just the EM, true?
>>>>>
>>>>>  Yes, but most components have no problems with getting accessed in
>>>> parallel. For managed Entities and EntityManagers it’s explicitly
>>>> forbidden
>>>> by the JPA spec.
>>>>
>>>> LieGrue,
>>>> strub
>>>>
>>>>
>>>
>

Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
Karl,

Mostly because ConversationScope beans must be serializable and the EM is not (check the "transient" keyword on the variable that 
keeps in the ConversationScope Holder) and the fact that in our web apps, the EM can be injected in components where the 
ConversationScope is not active (Namely MDBs and JAX-WS endpoints), where there is only one "request" and no need to get the same 
EM. For this we use another layer (Check my previous posts about our the "EntityResolver" interface and implementations)

Denis

Le 2015-04-19 14:33, Karl Kildén a écrit :
> Denis,
>
> What's the added benefit of wrapping the em in @ConversationScoped instead
> of exposing it like this directly. I am also porting a huge seam app (about
> 1k views) so I do need extended em.
>
> cheers
>
> On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:
>
>>
>> Le 2015-04-19 11:24, Mark Struberg a écrit :
>>
>>> Hi Dennis!
>>>
>>>
>>>   Have you *ever* hit this situation?
>>> Yes, under heavy load it happens pretty often actually (I’m talking about
>>> multi-million request/day public internet apps). It also depends a bit on
>>> the JPA container you use. From the pure spec it is forbitten to touch the
>>> EntityManager in parallel threads and also to touch managed (‚attached’)
>>> entities in parallel threads. What JPA container are you using?
>>>
>> Here we are talking about one ONE EM per ONE CDI Conversation.
>> So you have  applications with multi-million request/day concurrently in
>> one CDI Conversation that may lead *often* to a misuse of the EM ?
>> Impressive... How do you do that: Ajax requests? Proprietary client
>> javascript framework?
>> Or you are talking about *not closed EM* because the @PreDestroy callback
>> method has not been called in some particulat situation (sendRedirect is
>> called and the new request is processed before the initial request)?
>> Sorry, Mark but you lost me.....
>> Denis
>>
>>
>>   Also, who programs a „sendRedirect" in the middle of a method that then
>>>> performs database access ..?
>>>>
>>> You don’t need to do database access even. It is enough that the
>>> entitymanager is not closed as per the spec.
>>>
>>>
>>>   Even so, this is pure theory, the chance are so tiny this happens…
>>> Then I had bad luck - quite often ;)
>>>
>>>
>>>   And If you think this *may* happen within one conversation, then change
>>>> the way redirects are send, or the way database is accessed in parallel in
>>>> Ajax requests. not the way EM is used IMHO
>>>>
>>> That might be a solution. Or force the EM to get closed before the
>>> redirect.
>>>
>>>   Also your remark on „unfinished thread" is valid for ANY
>>>> components/resources held in ConversationScope, not just the EM, true?
>>>>
>>> Yes, but most components have no problems with getting accessed in
>>> parallel. For managed Entities and EntityManagers it’s explicitly forbidden
>>> by the JPA spec.
>>>
>>> LieGrue,
>>> strub
>>>
>>


Re: Extended EntityManager

Posted by Karl Kildén <ka...@gmail.com>.
Denis,

What's the added benefit of wrapping the em in @ConversationScoped instead
of exposing it like this directly. I am also porting a huge seam app (about
1k views) so I do need extended em.

cheers

On 19 April 2015 at 19:20, titou10 <ti...@gmail.com> wrote:

>
>
> Le 2015-04-19 11:24, Mark Struberg a écrit :
>
>> Hi Dennis!
>>
>>
>>  Have you *ever* hit this situation?
>>>
>> Yes, under heavy load it happens pretty often actually (I’m talking about
>> multi-million request/day public internet apps). It also depends a bit on
>> the JPA container you use. From the pure spec it is forbitten to touch the
>> EntityManager in parallel threads and also to touch managed (‚attached’)
>> entities in parallel threads. What JPA container are you using?
>>
> Here we are talking about one ONE EM per ONE CDI Conversation.
> So you have  applications with multi-million request/day concurrently in
> one CDI Conversation that may lead *often* to a misuse of the EM ?
> Impressive... How do you do that: Ajax requests? Proprietary client
> javascript framework?
> Or you are talking about *not closed EM* because the @PreDestroy callback
> method has not been called in some particulat situation (sendRedirect is
> called and the new request is processed before the initial request)?
> Sorry, Mark but you lost me.....
> Denis
>
>
>  Also, who programs a „sendRedirect" in the middle of a method that then
>>> performs database access ..?
>>>
>> You don’t need to do database access even. It is enough that the
>> entitymanager is not closed as per the spec.
>>
>>
>>  Even so, this is pure theory, the chance are so tiny this happens…
>>>
>> Then I had bad luck - quite often ;)
>>
>>
>>  And If you think this *may* happen within one conversation, then change
>>> the way redirects are send, or the way database is accessed in parallel in
>>> Ajax requests. not the way EM is used IMHO
>>>
>> That might be a solution. Or force the EM to get closed before the
>> redirect.
>>
>>  Also your remark on „unfinished thread" is valid for ANY
>>> components/resources held in ConversationScope, not just the EM, true?
>>>
>> Yes, but most components have no problems with getting accessed in
>> parallel. For managed Entities and EntityManagers it’s explicitly forbidden
>> by the JPA spec.
>>
>> LieGrue,
>> strub
>>
>
>

Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.

Le 2015-04-19 11:24, Mark Struberg a écrit :
> Hi Dennis!
>
>
>> Have you *ever* hit this situation?
> Yes, under heavy load it happens pretty often actually (I’m talking about multi-million request/day public internet apps). It also depends a bit on the JPA container you use. From the pure spec it is forbitten to touch the EntityManager in parallel threads and also to touch managed (‚attached’) entities in parallel threads. What JPA container are you using?
Here we are talking about one ONE EM per ONE CDI Conversation.
So you have  applications with multi-million request/day concurrently in one CDI Conversation that may lead *often* to a misuse of 
the EM ?
Impressive... How do you do that: Ajax requests? Proprietary client javascript framework?
Or you are talking about *not closed EM* because the @PreDestroy callback method has not been called in some particulat situation 
(sendRedirect is called and the new request is processed before the initial request)?
Sorry, Mark but you lost me.....
Denis

>> Also, who programs a „sendRedirect" in the middle of a method that then performs database access ..?
> You don’t need to do database access even. It is enough that the entitymanager is not closed as per the spec.
>
>
>> Even so, this is pure theory, the chance are so tiny this happens…
> Then I had bad luck - quite often ;)
>
>
>> And If you think this *may* happen within one conversation, then change the way redirects are send, or the way database is accessed in parallel in Ajax requests. not the way EM is used IMHO
> That might be a solution. Or force the EM to get closed before the redirect.
>
>> Also your remark on „unfinished thread" is valid for ANY components/resources held in ConversationScope, not just the EM, true?
> Yes, but most components have no problems with getting accessed in parallel. For managed Entities and EntityManagers it’s explicitly forbidden by the JPA spec.
>
> LieGrue,
> strub


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
Hi Dennis!


> Have you *ever* hit this situation?
Yes, under heavy load it happens pretty often actually (I’m talking about multi-million request/day public internet apps). It also depends a bit on the JPA container you use. From the pure spec it is forbitten to touch the EntityManager in parallel threads and also to touch managed (‚attached’) entities in parallel threads. What JPA container are you using?


> Also, who programs a „sendRedirect" in the middle of a method that then performs database access ..?

You don’t need to do database access even. It is enough that the entitymanager is not closed as per the spec.


> Even so, this is pure theory, the chance are so tiny this happens…
Then I had bad luck - quite often ;)


> And If you think this *may* happen within one conversation, then change the way redirects are send, or the way database is accessed in parallel in Ajax requests. not the way EM is used IMHO

That might be a solution. Or force the EM to get closed before the redirect.

> Also your remark on „unfinished thread" is valid for ANY components/resources held in ConversationScope, not just the EM, true?

Yes, but most components have no problems with getting accessed in parallel. For managed Entities and EntityManagers it’s explicitly forbidden by the JPA spec.

LieGrue,
strub

Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
I understand your points but, it is not a problem, at least for us.

Le 2015-04-19 04:59, Mark Struberg a écrit :
> Ah oki, I see. Didn’t catch that you store it away.
>
> There are quite a few tricky parts in practice with that approach (been there, done that..). Not ultimately problems but at least points you need to be aware off.
>
> The first one is the serialisation issue I talked about in my blog post already.
true. But not a problem for us, we use "session affinity routing" and no session/SFSB replication (too costly for the benefits it 
provides). We also blocked AS passivation
> The second one is that you must not touch the same EntityManager in parallel requests. But as the ConversationContexts is basically just a fraction of the Session (and gets stored in there), you will likely hit that.
>
> E.g. imagine a sendRedirect call in the middle of request A. Purely calling sendRedirect will _not_ finish the thread which contains request A. It might still need to do some work, e.g. send a message, clean up stuff etc. The problem now happens if your clients browser executes the redirect faster (resulting in Request B) than you could finish Request A. And in that case your app will blow up by accessing the same EM from 2 different threads.
For parallel access, you are talking here on parallel requests for ONE user within a Conversation (Most likely Ajax requests I 
guess) that will perform database updates access in parallel...
Have you *ever* hit this situation? Also, who programs a "sendRedirect" in the middle of a method that then performs database access 
..? Even so, this is pure theory, the chance are so tiny this happens...And If you think this *may* happen within one conversation, 
then change the way redirects are send, or the way database is accessed in parallel in Ajax requests. not the way EM is used IMHO
Also your remark on "unfinished thread" is valid for ANY components/resources held in ConversationScope, not just the EM, true?

> You will most likely not hit this issue during testing but _only_ under high load in production :(
We never never never hit that with many applications in production with this pattern, and strong performance/load/stress tests 
before going to prod.
However, it is true that we never specifically stressed tons of Ajax/parallel/unfinished/redirect  requests for ONE user in its 
session that perform database updates/access.
In fact with have not even one use case like that...
>
> LieGrue,
> strub
Well, again, this pattern works perfectly well for us, we never had performance/integrity/parallel problems, it solves many other 
small problems with the EM and IMHO it is the best way to migrate from Seam 2 and continue to use one the Seam 2 paradigm.
It's just an option for you to use...or not. Having choice is fun.

Denis
>
>
>> Am 18.04.2015 um 13:34 schrieb titou10 <ti...@gmail.com>:
>>
>> Mark,
>> We keep the EM in the conversation scope, but we expose it at the request scope
>> A new EM is created only when there is no one currently in the conversation scope, so we have the same EM for the duration of the conversation, short or long:
>> It is very close to what Seam 2 did
>>
>> @ConversationScoped
>> public class EntityManagerProducer {
>>
>> =====>   private transient EntityManager em;
>>
>>    @PersistenceUnit
>>    private EntityManagerFactory    emf;
>>
>>    @Produces
>>    @RequestScoped
>>    protected EntityManager creerEntityManager() {
>> ======>      if (em == null) {
>> ======>         em = emf.createEntityManager();
>> ======>      }
>> ======>      return this.em;
>>    }
>>
>> Le 2015-04-18 01:35, Mark Struberg a écrit :
>>> But in your example only the bean ‚holding‘ the producer method is @ConversationScoped. The EntityManager you create is only @RequestScoped (which is good imo!), right? So the lifecycle of the EM will effectively be 1-per-prequest.
>>>
>>> LieGrue,
>>> strub
>>>
>>>
>>>> Am 17.04.2015 um 22:30 schrieb titou10 <ti...@gmail.com>:
>>>>
>>>> I can't comment on the DS/JPA example, but that's why the solution we use keeps the EM instance in a variable, variable held in the @ConversationScoped Bean that "contains" the producer that "exposes" this EM in the @RequestScope
>>>> The EM is opened/closed only on conversation boundaries (short or long) , very similar to what Seam 2 does (In CDI,  Conversations length is not exactly the same as in Seam Conversations)
>>>> Denis
>>>>
>>>> Le 2015-04-17 16:05, Ludovic Pénet a écrit :
>>>>> Thanks to everybody for your valuable adviced.
>>>>>
>>>>> I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
>>>>> ExtendedEntityManager is identical to DS JPA example.
>>>>>
>>>>> So, something very close from DS JPA page example.
>>>>>
>>>>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>>>>
>>>>> In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.
>>>>>
>>>>> So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...
>>>>>
>>>>> Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?
>>>>>
>>>>> Ludovic
>>>>>
>>>>>


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
Ah oki, I see. Didn’t catch that you store it away.

There are quite a few tricky parts in practice with that approach (been there, done that..). Not ultimately problems but at least points you need to be aware off.

The first one is the serialisation issue I talked about in my blog post already.
The second one is that you must not touch the same EntityManager in parallel requests. But as the ConversationContexts is basically just a fraction of the Session (and gets stored in there), you will likely hit that.

E.g. imagine a sendRedirect call in the middle of request A. Purely calling sendRedirect will _not_ finish the thread which contains request A. It might still need to do some work, e.g. send a message, clean up stuff etc. The problem now happens if your clients browser executes the redirect faster (resulting in Request B) than you could finish Request A. And in that case your app will blow up by accessing the same EM from 2 different threads. 

You will most likely not hit this issue during testing but _only_ under high load in production :(


LieGrue,
strub



> Am 18.04.2015 um 13:34 schrieb titou10 <ti...@gmail.com>:
> 
> Mark,
> We keep the EM in the conversation scope, but we expose it at the request scope
> A new EM is created only when there is no one currently in the conversation scope, so we have the same EM for the duration of the conversation, short or long:
> It is very close to what Seam 2 did
> 
> @ConversationScoped
> public class EntityManagerProducer {
> 
> =====>   private transient EntityManager em;
> 
>   @PersistenceUnit
>   private EntityManagerFactory    emf;
> 
>   @Produces
>   @RequestScoped
>   protected EntityManager creerEntityManager() {
> ======>      if (em == null) {
> ======>         em = emf.createEntityManager();
> ======>      }
> ======>      return this.em;
>   }
> 
> Le 2015-04-18 01:35, Mark Struberg a écrit :
>> But in your example only the bean ‚holding‘ the producer method is @ConversationScoped. The EntityManager you create is only @RequestScoped (which is good imo!), right? So the lifecycle of the EM will effectively be 1-per-prequest.
>> 
>> LieGrue,
>> strub
>> 
>> 
>>> Am 17.04.2015 um 22:30 schrieb titou10 <ti...@gmail.com>:
>>> 
>>> I can't comment on the DS/JPA example, but that's why the solution we use keeps the EM instance in a variable, variable held in the @ConversationScoped Bean that "contains" the producer that "exposes" this EM in the @RequestScope
>>> The EM is opened/closed only on conversation boundaries (short or long) , very similar to what Seam 2 does (In CDI,  Conversations length is not exactly the same as in Seam Conversations)
>>> Denis
>>> 
>>> Le 2015-04-17 16:05, Ludovic Pénet a écrit :
>>>> Thanks to everybody for your valuable adviced.
>>>> 
>>>> I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
>>>> ExtendedEntityManager is identical to DS JPA example.
>>>> 
>>>> So, something very close from DS JPA page example.
>>>> 
>>>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>>> 
>>>> In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.
>>>> 
>>>> So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...
>>>> 
>>>> Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?
>>>> 
>>>> Ludovic
>>>> 
>>>> 
> 


Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
Mark,
We keep the EM in the conversation scope, but we expose it at the request scope
A new EM is created only when there is no one currently in the conversation scope, so we have the same EM for the duration of the 
conversation, short or long:
It is very close to what Seam 2 did

@ConversationScoped
public class EntityManagerProducer {

=====>   private transient EntityManager em;

    @PersistenceUnit
    private EntityManagerFactory    emf;

    @Produces
    @RequestScoped
    protected EntityManager creerEntityManager() {
======>      if (em == null) {
======>         em = emf.createEntityManager();
======>      }
======>      return this.em;
    }

Le 2015-04-18 01:35, Mark Struberg a écrit :
> But in your example only the bean ‚holding‘ the producer method is @ConversationScoped. The EntityManager you create is only @RequestScoped (which is good imo!), right? So the lifecycle of the EM will effectively be 1-per-prequest.
>
> LieGrue,
> strub
>
>
>> Am 17.04.2015 um 22:30 schrieb titou10 <ti...@gmail.com>:
>>
>> I can't comment on the DS/JPA example, but that's why the solution we use keeps the EM instance in a variable, variable held in the @ConversationScoped Bean that "contains" the producer that "exposes" this EM in the @RequestScope
>> The EM is opened/closed only on conversation boundaries (short or long) , very similar to what Seam 2 does (In CDI,  Conversations length is not exactly the same as in Seam Conversations)
>> Denis
>>
>> Le 2015-04-17 16:05, Ludovic Pénet a écrit :
>>> Thanks to everybody for your valuable adviced.
>>>
>>> I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
>>> ExtendedEntityManager is identical to DS JPA example.
>>>
>>> So, something very close from DS JPA page example.
>>>
>>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>>
>>> In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.
>>>
>>> So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...
>>>
>>> Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?
>>>
>>> Ludovic
>>>
>>>


Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
But in your example only the bean ‚holding‘ the producer method is @ConversationScoped. The EntityManager you create is only @RequestScoped (which is good imo!), right? So the lifecycle of the EM will effectively be 1-per-prequest. 

LieGrue,
strub


> Am 17.04.2015 um 22:30 schrieb titou10 <ti...@gmail.com>:
> 
> I can't comment on the DS/JPA example, but that's why the solution we use keeps the EM instance in a variable, variable held in the @ConversationScoped Bean that "contains" the producer that "exposes" this EM in the @RequestScope
> The EM is opened/closed only on conversation boundaries (short or long) , very similar to what Seam 2 does (In CDI,  Conversations length is not exactly the same as in Seam Conversations)
> Denis
> 
> Le 2015-04-17 16:05, Ludovic Pénet a écrit :
>> Thanks to everybody for your valuable adviced.
>> 
>> I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
>> ExtendedEntityManager is identical to DS JPA example.
>> 
>> So, something very close from DS JPA page example.
>> 
>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>> 
>> In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.
>> 
>> So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...
>> 
>> Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?
>> 
>> Ludovic
>> 
>> 
> 


Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
I can't comment on the DS/JPA example, but that's why the solution we use keeps the EM instance in a variable, variable held in the 
@ConversationScoped Bean that "contains" the producer that "exposes" this EM in the @RequestScope
The EM is opened/closed only on conversation boundaries (short or long) , very similar to what Seam 2 does (In CDI,  Conversations 
length is not exactly the same as in Seam Conversations)
Denis

Le 2015-04-17 16:05, Ludovic Pénet a écrit :
> Thanks to everybody for your valuable adviced.
>
> I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
> ExtendedEntityManager is identical to DS JPA example.
>
> So, something very close from DS JPA page example.
>
> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>
> In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.
>
> So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...
>
> Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?
>
> Ludovic
>
>


Re: Extended EntityManager

Posted by Ludovic Pénet <l....@senat.fr>.
Thanks to everybody for your valuable adviced.

I ended with an @ApplicationScoped EntityManagerProducer, producing @ViewAccessScoped ExtendedEntityManager.
ExtendedEntityManager is identical to DS JPA example.

So, something very close from DS JPA page example.

http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts

In fact, I am still a bit puzzled by DS JPA example, because the EntityManager it produces is @RequestScoped.

So, when I basically copied/pasted it, the EM was just opened and closed on every request. And, for an example, session was closed when some hibernate proxies were accessed during serialization...

Do I miss something obvious, or should the doc rather mention that one should use a scope such as @ViewScoped, @SessionScoped or @ViewAccessScoped rather than @RequestScoped ?

Ludovic


-- 
Envoyé de mon téléphone Android avec K-9 Mail. Excusez la brièveté.
|
| AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
|

Re: Extended EntityManager

Posted by Mark Struberg <st...@yahoo.de>.
I think it’s easier to make the class which contains the producer @AppliationScoped. That should work well. Please note that injecting a @PersistenceUnit is fine but a @PersistenceContext is _only_ allowed (as per spec) if you run ‚inside an EJB‘. 

LieGrue,
strub

> Am 17.04.2015 um 18:30 schrieb Rafael Pestano <rm...@gmail.com>:
> 
> Hi Denis,
> for situations where the scope is not active we use an interceptor to
> activate it, see this example:
> 
> http://gist.asciidoctor.org/?14312d475ab402768783
> 
> 
> 
> 2015-04-17 13:17 GMT-03:00 titou10 <ti...@gmail.com>:
> 
>> Ludovic,
>> I don't know if it may be of some help for you, but we have a lot of seam2
>> apps that we migrated to CDI and we had to face the problems you describe
>> (With many other..)
>> We tried first to use CODI then DeltaSpike, in its early days but we ended
>> to create our own CDIUtils libs..
>> To solve the problem, we exposed the EM in RequestScoped but it is kept
>> internally a ConversationScoped Bean holder:
>> So when a LRC is on, we always get the same EM
>> 
>> @ConversationScoped
>> public class EntityManagerProducer {
>>   private transient EntityManager em;
>> 
>>   @PersistenceUnit
>>   private EntityManagerFactory    emf;
>> 
>>   @Produces
>>   @RequestScoped
>>   protected EntityManager creerEntityManager() {
>>      // On n'a pas de EM en scope conversation, on en récupère un...
>>      if (em == null) {
>>         em = emf.createEntityManager();
>>      }
>>      return this.em;
>>   }
>> 
>>   @PreDestroy
>>   public void terminer() {
>>      if (em != null) {
>>         if (em.isOpen()) {
>>            log.trace("close em {}", em);
>>            em.close();
>>         }
>>      }
>>      em = null;
>>   }
>> }
>> 
>> Also the EM is not directly injected into Beans as our "Business Objects"
>> are held in a jar and the jar may be used in 3 different contexts:
>> - online/web in EJB3 SFSB,SLSB
>> - online in MDB or Web Services beans (No conversationscope here, but
>> @PersistenceUnit IS available)
>> - in batchs/JUnit (No conversationscope here, and no@PersistenceUnit
>> available from J2SE)
>> 
>> We have an interface called "EMResolver" that is injected in BO beans:
>> public interface EntityManagerResolver {
>>   EntityManager getEm();
>> }
>> 
>> with 2 different implentations, one onlie, one for batchs (that is
>> declared as an @Alternative)
>> The online implementation is:
>> @Stateless
>> public class EntityManagerResolverOnline implements EntityManagerResolver {
>>   @PersistenceContext
>>   private EntityManager           emFromEJB;
>> 
>>   @Inject
>>   private Instance<EntityManager> emLazyInstance;
>> 
>>   public EntityManager getEm() {
>>      Boolean estMDBouWS = ThreadLocalContextHolder.isMDBorWS();
>>      if (estMDBouWS) {
>>         log.trace("Contexte online MDB ou WS - EntityManager vient de
>> @PersistenceContext.");
>>         return emFromEJB;
>>      } else {
>>         log.trace("Contexte online non MDB ni WS - EntityManager vient de
>> CDI. +joinTransaction");
>>         EntityManager em = emLazyInstance.get();
>>         em.joinTransaction();
>>         return em;
>>      }
>>   }
>> }
>> The ThreadLocalContextHolder keep a boolean "threadlocal" variable set by
>> MDBs (from MDB own superclass) or WS (JAX-WS own handler)
>> 
>> The batch implementation:
>> @Alternative
>> @ApplicationScoped
>> public class EntityManagerBatchResolver implements EntityManagerResolver {
>> 
>>   private EntityManagerFactory emf;
>>   private EntityManager        em;
>> 
>>   @PostConstruct
>>   public void initialiser() {
>>      log.debug("@PostConstruct. Utilisation de
>> EntityManagerBatchResolver");
>>      emf = Persistence.createEntityManagerFactory(<name of the PU here>);
>>      em = emf.createEntityManager();
>>   }
>> 
>>   @PreDestroy
>>   public void terminer() {
>>      log.debug("@PreDestroy. terminer");
>>      emf.close();
>>   }
>> 
>>   public EntityManager getEm() {
>>      return em;
>>   }
>> }
>> 
>> Maybe it is not very academic but it works perfectly well for us and made
>> our move from seam 2 smotth..
>> 
>> Hope this helps..
>> 
>> Denis
>> 
>> 
>> Le 2015-04-17 05:37, l.penet@senat.fr a écrit :
>> 
>>> Dear all,
>>> 
>>> I am actually trying to switch from "raw" Hibernate to JPA.
>>> 
>>> I have the typical "keep the same entitymanager" during a scenario
>>> problem. IMHO, merging huge collections of entities is a nightmare that is
>>> not worth the cost when you deal with applications with a lot of business
>>> logic but few users and a low load. I fully endorse the "entitymanager per
>>> request" pattern for application having high trafic, and so need to be
>>> stateless, replicated, etc. but it does not appear to me to be the magic
>>> solution to all problems.
>>> 
>>> With hibernate, I historically solved it with the "open session in view"
>>> pattern. It is ugly when evaluated according to actual standards, but it
>>> works.
>>> 
>>>    https://developer.jboss.org/wiki/OpenSessionInView
>>> 
>>> When I tried to find the equivalent for JPA, I basically found
>>> 
>>> @PersistenceContext(type=PersistenceContextType.EXTENDED)
>>> 
>>> ...which could be a fit if I was using container managed datasources
>>> 
>>> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when
>>> I use application managed EntityManager-s, they are all created with
>>> PersistenceContextType.EXTENDED, and that this attribute is finally passed
>>> to :
>>> AbstractEntityManagerImpl base class constructor :
>>> 
>>>    protected AbstractEntityManagerImpl(
>>>            EntityManagerFactoryImpl entityManagerFactory,
>>>            PersistenceContextType type,  // TODO:  remove as no longer
>>> used
>>>            SynchronizationType synchronizationType,
>>> 
>>> and is just ignored. :-)
>>> 
>>> On this blog (I like good authors ;-) )
>>> https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/
>>> , I found mention of Avaje, which could be a fit if it was more of a
>>> standard.
>>> 
>>> I also fond on the net references to CODI, MyFaces Orchestra and Seam
>>> solutions to this problem. Most of the type it was also indicated that
>>> Deltaspike is "the way to go". An affirmation that is clearly also mine in
>>> general.
>>> However, I did not find a ready-to-use solution in the doc
>>> 
>>> 
>>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>> 
>>> I was a bit surprised, as some people stated that Seam code was to be
>>> merged in Deltaspike not to find a turn key solution.
>>> 
>>> Did I miss / misunderstood something ?
>>> 
>>> This is not a blocking problem to me. I can just use plain hibernate or
>>> unwrapped jpa/hibernate sessions and it will work... But I would like to
>>> understand. :-)
>>> 
>>> Thanks in advance,
>>> 
>>> Ludovic
>>> 
>>> 
>>> |
>>> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
>>> |
>>> 
>>> 
>> 
> 
> 
> -- 
> <http://www.advancedit.com.br/>Att,
> 
> Rafael M. Pestano
> 
> Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
> http://rpestano.wordpress.com/
> @realpestano <https://twitter.com/realpestano>


Re: Extended EntityManager

Posted by Rafael Pestano <rm...@gmail.com>.
Hi Denis,
for situations where the scope is not active we use an interceptor to
activate it, see this example:

http://gist.asciidoctor.org/?14312d475ab402768783



2015-04-17 13:17 GMT-03:00 titou10 <ti...@gmail.com>:

> Ludovic,
> I don't know if it may be of some help for you, but we have a lot of seam2
> apps that we migrated to CDI and we had to face the problems you describe
> (With many other..)
> We tried first to use CODI then DeltaSpike, in its early days but we ended
> to create our own CDIUtils libs..
> To solve the problem, we exposed the EM in RequestScoped but it is kept
> internally a ConversationScoped Bean holder:
> So when a LRC is on, we always get the same EM
>
> @ConversationScoped
> public class EntityManagerProducer {
>    private transient EntityManager em;
>
>    @PersistenceUnit
>    private EntityManagerFactory    emf;
>
>    @Produces
>    @RequestScoped
>    protected EntityManager creerEntityManager() {
>       // On n'a pas de EM en scope conversation, on en récupère un...
>       if (em == null) {
>          em = emf.createEntityManager();
>       }
>       return this.em;
>    }
>
>    @PreDestroy
>    public void terminer() {
>       if (em != null) {
>          if (em.isOpen()) {
>             log.trace("close em {}", em);
>             em.close();
>          }
>       }
>       em = null;
>    }
> }
>
> Also the EM is not directly injected into Beans as our "Business Objects"
> are held in a jar and the jar may be used in 3 different contexts:
> - online/web in EJB3 SFSB,SLSB
> - online in MDB or Web Services beans (No conversationscope here, but
> @PersistenceUnit IS available)
> - in batchs/JUnit (No conversationscope here, and no@PersistenceUnit
> available from J2SE)
>
> We have an interface called "EMResolver" that is injected in BO beans:
> public interface EntityManagerResolver {
>    EntityManager getEm();
> }
>
> with 2 different implentations, one onlie, one for batchs (that is
> declared as an @Alternative)
> The online implementation is:
> @Stateless
> public class EntityManagerResolverOnline implements EntityManagerResolver {
>    @PersistenceContext
>    private EntityManager           emFromEJB;
>
>    @Inject
>    private Instance<EntityManager> emLazyInstance;
>
>    public EntityManager getEm() {
>       Boolean estMDBouWS = ThreadLocalContextHolder.isMDBorWS();
>       if (estMDBouWS) {
>          log.trace("Contexte online MDB ou WS - EntityManager vient de
> @PersistenceContext.");
>          return emFromEJB;
>       } else {
>          log.trace("Contexte online non MDB ni WS - EntityManager vient de
> CDI. +joinTransaction");
>          EntityManager em = emLazyInstance.get();
>          em.joinTransaction();
>          return em;
>       }
>    }
> }
> The ThreadLocalContextHolder keep a boolean "threadlocal" variable set by
> MDBs (from MDB own superclass) or WS (JAX-WS own handler)
>
> The batch implementation:
> @Alternative
> @ApplicationScoped
> public class EntityManagerBatchResolver implements EntityManagerResolver {
>
>    private EntityManagerFactory emf;
>    private EntityManager        em;
>
>    @PostConstruct
>    public void initialiser() {
>       log.debug("@PostConstruct. Utilisation de
> EntityManagerBatchResolver");
>       emf = Persistence.createEntityManagerFactory(<name of the PU here>);
>       em = emf.createEntityManager();
>    }
>
>    @PreDestroy
>    public void terminer() {
>       log.debug("@PreDestroy. terminer");
>       emf.close();
>    }
>
>    public EntityManager getEm() {
>       return em;
>    }
> }
>
> Maybe it is not very academic but it works perfectly well for us and made
> our move from seam 2 smotth..
>
> Hope this helps..
>
> Denis
>
>
> Le 2015-04-17 05:37, l.penet@senat.fr a écrit :
>
>> Dear all,
>>
>> I am actually trying to switch from "raw" Hibernate to JPA.
>>
>> I have the typical "keep the same entitymanager" during a scenario
>> problem. IMHO, merging huge collections of entities is a nightmare that is
>> not worth the cost when you deal with applications with a lot of business
>> logic but few users and a low load. I fully endorse the "entitymanager per
>> request" pattern for application having high trafic, and so need to be
>> stateless, replicated, etc. but it does not appear to me to be the magic
>> solution to all problems.
>>
>> With hibernate, I historically solved it with the "open session in view"
>> pattern. It is ugly when evaluated according to actual standards, but it
>> works.
>>
>>     https://developer.jboss.org/wiki/OpenSessionInView
>>
>> When I tried to find the equivalent for JPA, I basically found
>>
>> @PersistenceContext(type=PersistenceContextType.EXTENDED)
>>
>> ...which could be a fit if I was using container managed datasources
>>
>> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when
>> I use application managed EntityManager-s, they are all created with
>> PersistenceContextType.EXTENDED, and that this attribute is finally passed
>> to :
>> AbstractEntityManagerImpl base class constructor :
>>
>>     protected AbstractEntityManagerImpl(
>>             EntityManagerFactoryImpl entityManagerFactory,
>>             PersistenceContextType type,  // TODO:  remove as no longer
>> used
>>             SynchronizationType synchronizationType,
>>
>> and is just ignored. :-)
>>
>> On this blog (I like good authors ;-) )
>> https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/
>> , I found mention of Avaje, which could be a fit if it was more of a
>> standard.
>>
>> I also fond on the net references to CODI, MyFaces Orchestra and Seam
>> solutions to this problem. Most of the type it was also indicated that
>> Deltaspike is "the way to go". An affirmation that is clearly also mine in
>> general.
>> However, I did not find a ready-to-use solution in the doc
>>
>>
>> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>>
>> I was a bit surprised, as some people stated that Seam code was to be
>> merged in Deltaspike not to find a turn key solution.
>>
>> Did I miss / misunderstood something ?
>>
>> This is not a blocking problem to me. I can just use plain hibernate or
>> unwrapped jpa/hibernate sessions and it will work... But I would like to
>> understand. :-)
>>
>> Thanks in advance,
>>
>> Ludovic
>>
>>
>> |
>> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
>> |
>>
>>
>


-- 
<http://www.advancedit.com.br/>Att,

Rafael M. Pestano

Desenvolvedor Java Cia. de Processamento de Dados do Rio Grande do Sul
http://rpestano.wordpress.com/
@realpestano <https://twitter.com/realpestano>

Re: Extended EntityManager

Posted by titou10 <ti...@gmail.com>.
Ludovic,
I don't know if it may be of some help for you, but we have a lot of seam2 apps that we migrated to CDI and we had to face the 
problems you describe (With many other..)
We tried first to use CODI then DeltaSpike, in its early days but we ended to create our own CDIUtils libs..
To solve the problem, we exposed the EM in RequestScoped but it is kept internally a ConversationScoped Bean holder:
So when a LRC is on, we always get the same EM

@ConversationScoped
public class EntityManagerProducer {
    private transient EntityManager em;

    @PersistenceUnit
    private EntityManagerFactory    emf;

    @Produces
    @RequestScoped
    protected EntityManager creerEntityManager() {
       // On n'a pas de EM en scope conversation, on en récupère un...
       if (em == null) {
          em = emf.createEntityManager();
       }
       return this.em;
    }

    @PreDestroy
    public void terminer() {
       if (em != null) {
          if (em.isOpen()) {
             log.trace("close em {}", em);
             em.close();
          }
       }
       em = null;
    }
}

Also the EM is not directly injected into Beans as our "Business Objects" are held in a jar and the jar may be used in 3 different 
contexts:
- online/web in EJB3 SFSB,SLSB
- online in MDB or Web Services beans (No conversationscope here, but @PersistenceUnit IS available)
- in batchs/JUnit (No conversationscope here, and no@PersistenceUnit available from J2SE)

We have an interface called "EMResolver" that is injected in BO beans:
public interface EntityManagerResolver {
    EntityManager getEm();
}

with 2 different implentations, one onlie, one for batchs (that is declared as an @Alternative)
The online implementation is:
@Stateless
public class EntityManagerResolverOnline implements EntityManagerResolver {
    @PersistenceContext
    private EntityManager           emFromEJB;

    @Inject
    private Instance<EntityManager> emLazyInstance;

    public EntityManager getEm() {
       Boolean estMDBouWS = ThreadLocalContextHolder.isMDBorWS();
       if (estMDBouWS) {
          log.trace("Contexte online MDB ou WS - EntityManager vient de @PersistenceContext.");
          return emFromEJB;
       } else {
          log.trace("Contexte online non MDB ni WS - EntityManager vient de CDI. +joinTransaction");
          EntityManager em = emLazyInstance.get();
          em.joinTransaction();
          return em;
       }
    }
}
The ThreadLocalContextHolder keep a boolean "threadlocal" variable set by MDBs (from MDB own superclass) or WS (JAX-WS own handler)

The batch implementation:
@Alternative
@ApplicationScoped
public class EntityManagerBatchResolver implements EntityManagerResolver {

    private EntityManagerFactory emf;
    private EntityManager        em;

    @PostConstruct
    public void initialiser() {
       log.debug("@PostConstruct. Utilisation de EntityManagerBatchResolver");
       emf = Persistence.createEntityManagerFactory(<name of the PU here>);
       em = emf.createEntityManager();
    }

    @PreDestroy
    public void terminer() {
       log.debug("@PreDestroy. terminer");
       emf.close();
    }

    public EntityManager getEm() {
       return em;
    }
}

Maybe it is not very academic but it works perfectly well for us and made our move from seam 2 smotth..

Hope this helps..

Denis

Le 2015-04-17 05:37, l.penet@senat.fr a écrit :
> Dear all,
>
> I am actually trying to switch from "raw" Hibernate to JPA.
>
> I have the typical "keep the same entitymanager" during a scenario problem. IMHO, merging huge collections of entities is a 
> nightmare that is not worth the cost when you deal with applications with a lot of business logic but few users and a low load. I 
> fully endorse the "entitymanager per request" pattern for application having high trafic, and so need to be stateless, replicated, 
> etc. but it does not appear to me to be the magic solution to all problems.
>
> With hibernate, I historically solved it with the "open session in view" pattern. It is ugly when evaluated according to actual 
> standards, but it works.
>
>     https://developer.jboss.org/wiki/OpenSessionInView
>
> When I tried to find the equivalent for JPA, I basically found
>
> @PersistenceContext(type=PersistenceContextType.EXTENDED)
>
> ...which could be a fit if I was using container managed datasources
>
> When digging the Hibernate 4.3.8 jpa implementation, I noticed that when I use application managed EntityManager-s, they are all 
> created with PersistenceContextType.EXTENDED, and that this attribute is finally passed to :
> AbstractEntityManagerImpl base class constructor :
>
>     protected AbstractEntityManagerImpl(
>             EntityManagerFactoryImpl entityManagerFactory,
>             PersistenceContextType type,  // TODO:  remove as no longer used
>             SynchronizationType synchronizationType,
>
> and is just ignored. :-)
>
> On this blog (I like good authors ;-) ) https://struberg.wordpress.com/2012/04/25/is-there-a-way-to-fix-the-jpa-entitymanager/ , I 
> found mention of Avaje, which could be a fit if it was more of a standard.
>
> I also fond on the net references to CODI, MyFaces Orchestra and Seam solutions to this problem. Most of the type it was also 
> indicated that Deltaspike is "the way to go". An affirmation that is clearly also mine in general.
> However, I did not find a ready-to-use solution in the doc
>
> http://deltaspike.apache.org/documentation/jpa.html#_extended_persistence_contexts
>
> I was a bit surprised, as some people stated that Seam code was to be merged in Deltaspike not to find a turn key solution.
>
> Did I miss / misunderstood something ?
>
> This is not a blocking problem to me. I can just use plain hibernate or unwrapped jpa/hibernate sessions and it will work... But I 
> would like to understand. :-)
>
> Thanks in advance,
>
> Ludovic
>
>
> |
> | AVANT D'IMPRIMER, PENSEZ A L'ENVIRONNEMENT.
> |
>