1

I have a code and I use envers and it works great. I get auditing on a separate _AUD table. But later, I need to use optimistic locking. But it does not work with @Audited annotation. Here is my code

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

The code should raise optimistict locking error, but it does not. Instead I get

Caused by: java.sql.SQLException: Field 'Version' doesn't have a default value.

But when I remove the @Audited annotation, the optimistic works and I get HibernateOptimisticLockingFailureException which is I am expecting. Is it known that these 2 annotation don't play nicely with each other? I also tried putting @NotAudited on the version column, but still don't work

1 Answers1

0

I was able to solve using discussion in Java - JPA - @Version annotation

I needed to have a default value on db level. On insert, there is no default value. But succeeding updates will increment and check optimistic locking

Community
  • 1
  • 1