我有一个代码,我使用envers,它的效果很好。我在单独的_AUD表上进行审核。但是稍后,我需要使用乐观锁定。但是它不适用于@Audited
注释。这是我的代码
@MappedSuperclass
@Audited
public class BaseVO implements IXtrainVO
{
@Version
@Column(name = "Version")
private long version;
}
@Entity
@Table(name = "Person")
@Audited
public class PersonVO extends BaseVO
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PersonId", unique = true, nullable = false)
private Long personId;
@Column(name = "Name", length = 80, nullable = false)
@NotBlank
@Size(max = 80)
private String name;
}
@Test
public void testLocking() throws Exception
{
PersonVO person = new PersonVO();
person.setName( "John" );
Long personId = personManager.savePerson( person );
PersonVO copy1 = personManager.findPerson( personId );
PersonVO copy2 = personManager.findPerson( personId );
copy1.setName( "John1" );
personManager.updatePerson( copy1 );
copy2.setName( "John2" );
personManager.updatePerson( copy2 );
}
该代码应引发乐观锁定错误,但事实并非如此。相反,我得到了
Caused by: java.sql.SQLException: Field 'Version' doesn't have a default value.
但是,当我删除
@Audited
批注时,乐观的工作原理得到了我期望的HibernateOptimisticLockingFailureException
。是否知道这两个注解不能很好地配合?我也尝试将@NotAudited
放在版本列上,但仍然无法正常工作 最佳答案
我能够使用Java - JPA - @Version annotation中的讨论来解决
我需要在数据库级别具有默认值。插入时,没有默认值。但是成功的更新将增加并检查乐观锁定