JPA合并引发StaleObjectStateException吗?

时间:2018-10-31 07:46:48

标签: java hibernate jpa

当我尝试创建四个客户时,有代码。 1.将Customer1,2写入数据库 2.合并Customer3(具有相同的ID,例如1) 3.合并Customer4(再次具有相同的ID) 我想创建同一实体的任何版本

所以

public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Info");
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        Customer customer1 = new Customer("1", "Vladislav");
        Customer customer2 = new Customer("2", "Maria");
        Customer customer3 = new Customer("1", "Ekaterina");
        Customer customer4 = new Customer("1", "Helen");

        entityManager.getTransaction().begin();
        entityManager.persist(customer1);
        entityManager.persist(customer2);
        entityManager.getTransaction().commit();

        entityManager.getTransaction().begin();
        entityManager.merge(customer3);
        entityManager.getTransaction().commit();

        entityManager.getTransaction().begin();
        entityManager.merge(customer4);
        entityManager.getTransaction().commit();

        //get versions here:
        entityManager = entityManagerFactory.createEntityManager();
        AuditReader auditReader = AuditReaderFactory.get(entityManager);
        List<Number> versions = auditReader.getRevisions(Customer.class, "1");
        System.out.println("========");
        System.out.println(Arrays.toString(versions.toArray()));

        entityManager.close();
        entityManagerFactory.close();
    }

客户实体:

package entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.envers.Audited;

import javax.persistence.*;


@Getter
@Setter
@NoArgsConstructor
@Entity
@Audited
public class Customer {
    @Id
    @Column(length = 100, nullable = false)
    private String id;
    private String name;

    @Version
    int version;

    public Customer(String id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", version=" + version +
                '}';
    }
}

当我只保留客户1,2,并合并客户3-一切正常时。

但是在我与customer4实体添加合并时-出现错误消息-

线程“主”中的异常javax.persistence.OptimisticLockException:该行已被另一个事务更新或删除(或未保存的值映射不正确):[entity.Customer#1] 引起原因:org.hibernate.StaleObjectStateException:行被另一个事务更新或删除(或未保存的值映射不正确):[entity.Customer#1]     ...还有2个

为什么我什么时候都不能合并?

1 个答案:

答案 0 :(得分:1)

您只能将客户与具有最新版本的实例合并。

customer1 version = 0

id ='1'的当前版本现在为0

customer3 version = 0 ,因此可以合并,合并后 version = 1

id ='1'的当前版本现在为1

customer4具有 version = 0 ,因此不再可能合并。