Search code examples
ormjpa-2.0eclipselink

How to implement a generic "saveOrUpdate" method with EclipseLink and JPA2


I'm trying to do a method like that, bug got concurrency problems.. seems like my update method do not increment the @Version attribute of my Entity.

My code is like that:

      @Transactional
      public B save(B bean) {
        if (bean == null || bean.getId() == null) {
            persist(bean);
        } else {
            bean = update(bean);
        }
        return bean;
      }     

      protected final B update(B bean) {
        bean = em().merge(bean);
        em().flush();
        return bean;
      }

This is a piece of code of my AbstractDao. The em() method return a EntityManager that is managed by Guice-Persist.

Also, I'm using eclipselink.

thanks in advance


Solution

  • I solve it with the following code:

    protected final void persist(B bean) {
        em().persist(bean);
    }
    
    protected final B update(B bean) {
        bean.setVersion(findById(bean.getId()).getVersion());
        bean = em().merge(bean);
        em().flush();
        return bean;
    }
    
    @Transactional
    public B save(B bean) {
        if (bean == null || bean.getId() == null) {
            persist(bean);
        } else {
            bean = update(bean);
        }
        return bean;
    }