I’m a novice.
Does Jersey and EJB hold the same EntityManager scope?
Should I have to pass the EntityManager to EJB for same persistence context?
The primary target usage is JTA.
@Stateless
class MyEJB {
public MyEntity find(Long id) {
...
}
@PersistenceContext;
EntityManager entityManager;
}
class MyResource {
@GET
@Path("/myentity/{id}");
public MyEntity get(@PathParam("id") final long id) {
final MyEntity found = myEjb.find(id);
// is found's state detached?
// should I have to reattach?
found.setDate(new Date());
return found;
}
@EJB
private MyEjb myEjb;
@PersistenceContext;
EntityManager entityManager;
}
I don’t think that your wording is correct, but they can share the same EntityManager instance, and you have chosen the right way (through injection). Have a look at this chapter of the Java EE 6 Tutorial:
So, once again, your approach is correct. With regards to the questions in the code comments: the fact that
MyEntityis attached or detached, it depends on the implementation of the find method in yourEJB. If you do the following, it will be attached:Finally, doing this way, if you have chosen
JTAto use container managed transactions, the transactions will be automatically bounded with the natural boundaries ofMyBean‘s methods. In order to have JTA transactions, you have to use this line inpersistence.xmlfile: