Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

EJB3/JPA: problem reloading object with one-to-many

 
Bear Giles
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm learning EJB3 and JPA and this might be an embarassingly stupid question. I'm following the conventions of injecting an entity manager factory into by stateless bean and creating an entity manager on initialization and closing it upon destruction.

This means that my one-to-many relationship crosses concurrent entity managers since it doesn't make sense to put both User (one) and Auction (many) operations into the same EJB bean.

The problem is that I can save a one-to-many relationship in the Auction bean but I don't see it via user.find() unless I immediately follow it with em.refresh(user).

Is there a way around this, e.g., having a shared entity manager cache? Calling refresh() hits the database so I would prefer to avoid it if possible.
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using a stateless SessionBean you should inject an EntityManager, not an EntityManagerFactory. The container will then ensure the correct EntityManager is used for the transaction.
 
Bear Giles
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I tried that earlier it looked like it required JTA. That's a little heavy when you're just running stuff as MyEclipse unit tests or a very simple webapp under tomcat. Did I miss something?

(I also have jboss installed but this is an older system so I try to avoid the memory load.)
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure how you are using EJB SessionBeans without JTA, as they are dependent on JTA. Also not sure how you are using SessionBeans on Tomcat, as it is not a JEE container.

For webapps not using SessionBeans, you don't need to use JTA, you normally create an EntityManager per server request. If you have a stateful architecture you may have an EntityManager per http session. I don't think having cached EntityManager per DAO or per service would be a good idea.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic