I'm working on a new J2EE-application, and is evaluating EJB3 as persistence layer. I'm quite new to J2EE and have a question about what's best practice regarding my PAR.
Now I've split my @Entity classes into two different PARs. One PAR contains entity A which depends on entity B in the second PAR (with a forreign key in the database). This works fine if I create both object A and B with new in the same Session in the same Stateless bean.
If I instead uses a different Stateless bean to retreive object B, I can't persist entity A (which references entity B) without first calling manager.refresh(b).
The following example will give me an Exception "detached entity passed to persist" on last line:
B entityB = otherStatelessBean.findMyB(); A entityA = new A(entityB); manager.persist(entityA);
B entityB = otherStatelessBean.findMyB(); manager.refresh(entityB); A entityA = new A(entityB); manager.persist(entityA);
related entity beans (ie associated) should be defined in the same persistence unit.
Regarding the issue, what you can do is load virtually B through em.getReference(), and associate it to A, this will not create an extra select.
or use em.merge(a) to avoid the exception and have only 1 api call.