hibernatejpa-2.0guice-persist

JPA2 + Hibernate + Guice-persist: Version Behavior


I using Hibernate 3.6 Final, Guice-persist and JPA2.

So good, I have everything configured, and my bean has a @Version private Long version;, with getter and setter.

I have implemented equals and hashcode with all the fields.

My dao save method is :

@Transactional
public void save(Product p){ em.persist(p); }

But, if I do something like:

Product p = new Product("name"); //id=null, version=null
dao.save(p); //works, id!=null, version=0
Product p2 = new Produto(10, 0, "other name"); //id, version, name
dao.save(p2); //works, but the version isnt updated, so my version still 0

Then, if I change the name and try to save again, I got a "StaleObjectstateException row was updated or deleted by ..."...

I like to know what am I have to do to make entity manager update the version when save the object... and why persist didn't do this.

Thanks in advance.


Solution

  • I solve this problem this way:

    @Transactional
    public void persist(B bean) {
        em.persist(bean);
    }
    
    @Transactional
    public B update(B bean) {
        bean = em.merge(bean);
        em.flush();
        return bean;
    }
    

    Then I just call the save method and this method know what it have to do:

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