Domanda

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.

È stato utile?

Soluzione 2

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

Altri suggerimenti

(Ignoring that the code says new Produto and not new Product) For p2, you are setting the id and version at object instatiation, then persisting it. After persisting the state of the object p2 is unchanged from the last known persisted state -> no need to update the version.

( Do something like p2.setName("yet another name"), then do p2.getVersion() ... to see the effect.

p otho didn't have any version, neither directly set by "you" via code or via the PresistenceContext. Once you persisted p, it got managed in a persistence context and hence got a version number - in this case it got version 0 (newly created).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top