Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stateful EJB with extended persistence context to handle user session

Tags:

java

jpa

jsf

cdi

ejb

I'm using a CDI session scoped bean to hold user related information (His user entity bean, credential, etc). I have a save method for everytime a user changes his info (like email, password, etc). However, I could have a stateful session bean with extended persistence context to do so. If I do that, his user entity will become managed during his session and changes to his email etc would be synchronized without recreating persistence contexts etc. Is this a good idea? Should I have an extended persistence context open for so long? This also locks changes to the user for external beans right? What if I have an administrator trying to make changes to this user (it could happen).

like image 716
arg20 Avatar asked Dec 30 '25 02:12

arg20


1 Answers

There are a couple of side-effects you need to beware of.

The first thing is that the extended persistence context you use to hold this user entity should not be used for much else, as it automatically caches everything being touched (the L1 cache).

If you need to use this continuously attached user entity in some other operation dealing with some other persistence context, you need to fetch a fresh instance instead of using the instance in session scope.

The locking thing does not happen automatically. Normally, different persistence contexts can also modify the same entity. Typically the last one to do any writes will 'win'. If you want to prevent this, you can take advantage of the normal locking operations in JPA. For this case, optimistic locks are probably best suited.

I'm curious though how well this will work in practice. It's surely a novel idea. From reading many blog posts, articles, books and discussions with many developers, I get the feeling that the extended persistence context is fairly little known thing and not that much best practices have been created for it.

The fact that Stateful session beans can now be scoped via CDI (and thus automatically destroyed when e.g. the HTTP session is destroyed) makes the entire concept much more viable. But CDI too is relatively new, and a lot of people still have to discover how to best use it.

like image 171
Arjan Tijms Avatar answered Dec 31 '25 14:12

Arjan Tijms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!