尝试在JPA实体中添加@Version时发生StaleObjectStateException

时间:2018-11-01 11:09:21

标签: java spring hibernate jpa version

我尝试在项目中使用休眠envers进行版本控制。 使用jpa,jpa信息库,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
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中的保存方法有关。如果实体存在,它将尝试将新实体与具有相同键的实体合并。

P.S。我有gor这个问题,但是我相信存在解决这个问题的正确方法。代替实体的其他时间savemerge,我是第一次写入base,有时是我从base读取并手动更新实体

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

0 个答案:

没有答案