I have been developing my web-app using JPA 2.0 implementation EclipseLink 2.2.0. I finally got around to running multi-threaded code and I got this exception:
java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManager.
The objects that have all the javax.persistence calls in my application are defined as application scoped, like this:
@Model
@ApplicationScoped
public class LocationControl implements Serializable {
@PersistenceContext private EntityManager em;
@Resource private UserTransaction utx;
// etc
And of course all the managed beans (usually RequestScoped or ConversationScoped) that want to access the data base do so like this:
@Inject private LocationControl lc;
So my question is this: Did I get that Exception through the use of @ApplicationScoped DAO? I had thought that it would be more efficient that way, since the container would not have to be continually re-creating this object开发者_高级运维 on every request if it did not have a scope, and the DAO has no state of its own. However if the EntityManager and UserTransaction object have to be separate instances for each user, then that would be a problem.
Alternatively, I could use syncrhonized on the DAO methods, but I think that would cause thread lockups in the container (GlassFish).
Any advice appreciated.
@Model annotation was originally created to annotate request scoped beans, here is how it's defined:
@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface Model {}
You can of course override '@RequestScoped' with another annotation but '@ApplicationScoped' it's not a good choice as everyone in the application would modify the state of the same injected EntityManager. I think it would be best to leave it @RequestScoped in most cases, sometimes, for example for a login/logout data bean '@SessionScoped' could be an option but I cannot see a scenario for '@ApplicationScoped' dao.
If you don't want to use @Model at all and you use full Java EE container, then the stateless EJB ,as BalusC said, would be a great option for Dao too.
精彩评论