OptimisticLockException when manually setting the ID for the entity

Hello,

In the Hibernate 6.5 version, we got a new behavior.
When we set the ID manually for the entity we got this exception:

jakarta.persistence.OptimisticLockException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I found the explanation for this behavior here:
6.6 Migration Guide (Merge versioned entity when row is deleted)

Actually, we set ID manually mainly in the Tests in our application. That code has worked well for many years and for now we need totally rework it.

The questions are:

  1. Is there some way to avoid that OptimisticLockException exception when we sitting ID manually at least for tests?
  2. Possibly we configured something wrong or my understanding of that behavior is incorrect?

Thank you!

This was a deliberate decision. I understand that testing might get more complicated, but you really shouldn’t rely on fixed id values if you have a generator. This can lead to lot’s of other problems.

I think if you’re using Quarkus, Spring or other containers, you should be able to create a class like this and mark it as a bean to make this work:

	public class SequenceOrAssignedGenerator extends SequenceStyleGenerator {
		@Override
		public Object generate(SharedSessionContractImplementor session, Object owner) throws HibernateException {
			final Long id;
			if ( owner instanceof MyEntity ) {
				id = ( (MyEntity) owner ).getId();
			}
			else {
				id = null;
			}

			return id != null ? id : super.generate( session, owner );
		}

		@Override
		public boolean allowAssignedIdentifiers() {
			return true;
		}
	}

Please let us know if it does. Maybe you can even contribute a section in the migration guide for ORM 6.6 that explains this “workaround”?

This can lead to lot’s of other problems.

Sure. We understand this. But we have some legacy code in the older version of our application and we don’t want to invest so much in that direction.

Please let us know if it does

Thanks! This magic property works for us.
We already had a custom IdGenerator with the logic that you have shared in the overridden generate method but without allowAssignedIdentifiers property it did not work.

Maybe you can even contribute a section in the migration guide for ORM 6.6 that explains this “workaround”?

Is there some link on how to do this?

Sure, here is the migration guide on GitHub. Here some details to getting started.

1 Like