我尝试在我的项目中使用hibernate envers进行版本控制 . 使用jpa,jpa repository,spring和hibernate作为提供者 .

有jpa实体

@Entity
@Audited
@IdClass(CusomerId.class)
@Table(name = "Cusomer", uniqueConstraints = {
        @UniqueConstraint(columnNames = { "name", "surname", "org" })})
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Setter
public class Customer {
    @Id
    @Column(name = "name", length = 100, unique = false, nullable = false)
    private String name;

    @Id
    @Column(name = "surname", length = 100, unique = false, nullable = false)
    private String surname;

    @Id
    @Column(name = "org", length = 100, unique = false, nullable = false)
    private String org;

    @Column(name = "metaInfo", length = 100, unique = false, nullable = true)
    private String metaInfo;

    public Customer(String name, String surname, String org, String metaInfo) {
        this.name=name;
        this.surname=surname;
        this.org=org;
        this.metaInfo=metaInfo;
    }
}

在应用程序中我使用Jpa Repository,因此,我的存储库看起来像

@Repository
public interface CustomerRepository extends CrudRepository<Customer, CutomerId>{}

在我的流程中,

Customer customer1 = new Customer("aaa", "bbb", "23", "this is secret info1")
Customer customer2 = new Customer("aaa", "bbb", "23", "this is secret info2 updated")
Customer customer3 = new Customer("aaa", "bbb", "23", "this is secret info3")

我打电话

customerRepository.save(customer1); 
customerRepository.save(customer2);
customerRepository.save(customer3);

代码工作正常,在基础上我已更新实体 . 但是,如果我添加到我的实体 @Version 版本;表,当我试图保存customer3时有 StaleObjectStateException .

我希望,这个问题与 SimpleJpaRepository 中的save方法有关 . 如果实体存在,则尝试将新实体与具有相同键的实体合并 .

附:我有w.a.这个问题,但我相信存在解决这个问题的正确方法 . 而不是 savemerge 其他时间的实体,我在第一次写入基地,有时我从基地读取并用手更新实体

public void add(String name, String surname, String age,
                    String metaInfo) {
        Customer customer = CustomerRepository.findRiskBustomerByNameAndSurnameAndAge(
                name, surname, age);

        if (customer == null) {
            customer = new Customer(name, surname,
                    age, metaInfo);

            customerRepository.save(customer);
        } else {
            customer.setMetaInfo(metaInfo);

        }
        customerRepository.save(customer);
    }