user8371723
user8371723

Reputation:

Hibernate @Version conflict with @Audited (probably)

I add to my Entity

@Version @Temporal(TemporalType.TIMESTAMP)
@Column(name = "version")
private Date version;

and something strange happend. When i update, hibernate tells thath key already exists. How @version filed affect my Entity? I have no idea why it happend. When i remove this @version field everything works. I also use @Audited annotation.

My Entity:

private static final long serialVersionUID = 1636824190907788517L;
@Id
@NotNull
@Column(name = "id")
private UUID id;
@Version
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "version")
private Date version;
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "user", nullable = false)
private User user;
@Column(name = "purpose", length = 100)
protected String comment;
@OneToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "eq_id", nullable = false)
protected BasicEquipment equip;
@OneToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "eq_id2", nullable = false)
protected BasicEquipment equip2;

Error:

Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement (...)

org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(Standaorg.hibernate.engine.jdbc.sporg.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatch org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTra Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "pk_entity"

Upvotes: 0

Views: 427

Answers (1)

SaAn
SaAn

Reputation: 452

Did you try this solution?

http://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking

Under some circumstances, problems may occur when versioned updates are used together with batch updates. It has happened to me in the past with a given version of Oracle 11g and Hibernate, for example. The Oracle JDBC driver was not able to extract the correct number of updated rows count in JDBC batch statements execution.

If you are also facing this problem, you may check if you have set the Hibernate property hibernate.jdbc.batch_versioned_data to true. When this setting is true, Hibernate will use batch updates even for updates that are made against versioned data, ie. updates that need to use the updated rows count in order to check for concurrent updates. Since the JDBC driver may not return the correct updated rows count, Hibernate will not be able to detect if concurrent updates actually happened. The default value for this setting in Hibernate is false, so it will not use batch updates when it detects that versioned data updates are going to be executed in a given flush operation.

This is of course a specific scenario with Oracle 11g that is easily worked around, as we have just seen.

Upvotes: 0

Related Questions