1 Reply Latest reply on Oct 3, 2005 12:12 PM by epbernard

    Questions about Best Practice for multiple PAR

    per.a.norman

      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);
      


      To solve this I can write:

      B entityB = otherStatelessBean.findMyB();
      manager.refresh(entityB);
      A entityA = new A(entityB);
      manager.persist(entityA);
      


      The refresh() will create a second (unnecessary) SELECT to the database.

      I split my classes because I wanted a modularized application with one PAR and one EJB3 (with session beans) in every module. The above example made me unsure if this is a good idea.

      My questions:
      * What is best practice when modularizing EJB3-applications?
      * Should I split entities or keep them together in one big PAR?
      * Is there another solution or pattern to use to solve my problem above?


      Thanks in advance!
      Per


        • 1. Re: Questions about Best Practice for multiple PAR
          epbernard

          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.