users@glassfish.java.net

em.merge after em.persist problem

From: <glassfish_at_javadesktop.org>
Date: Mon, 09 Nov 2009 19:02:27 PST

I have a class that creates an entity bean. I have a EJB that call this class to create the entity bean, and, if certain condition is met, modify the entity bean. But the problem is, both create and modify write a different row to the database, one is before the modification and one is after.

The java class that create the entity bean looks like this:
        Context c = new InitialContext();
        StockFacadeRemote stkMaint = (StockFacadeRemote) c.lookup("StockFacade");
        stkMaint.create(myStock);

StockFacade looks like this:
      @PersistenceContext
      private EntityManager em;
      public void create(Stock stock) {
          em.persist(stock);
      }
      public void edit(Stock stock) {
          em.merge(stock);
      }

My EJB that calls the java class and modify the entity bean looks like this:
     @EJB
     StockFacadeRemote stkMaint;
     ... call java class to create stock, return myStock ....
     if (condition met) {
          myStock.setName("done");
          stkMaint.edit(myStock);
      }
After execution, 2 rows found in the DB instead of 1, one with original Name and another with Name="done". What have I missed in my coding?

Without knowing why, I tried this in my java class and it fixed the problem:
        stkMaint.create(myStock);
        myStock = stkMaint.find(myStock.getCode());
Certainly this is not the proper way to do it. Please help.
[Message sent by forum member 'senderj' (senderj_at_hotmail.com)]

http://forums.java.net/jive/thread.jspa?messageID=371222