How to implement a common saveOrUpdate method with EclipseLink and JPA2

I am trying to make such a method, the problem is with the concurrency error .. it looks like my update method does not increase the @Version attribute of my object.

My code looks like this:

      @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 part of the code of my AbstractDao. The em () method returns an EntityManager that is managed by Guice-Persist.

In addition, I use eclipselink.

early

+3
source share
1 answer

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;
}
+1
source

All Articles