id is generated and set beforehand manually for a new entity, then I use repo's save method to save it but it throws exception:

org.springframework.transaction.HeuristicCompletionException, message=Heuristic completion: outcome state is rolled back; nested exception is org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [PersonEntity_AUDIT#{REVISION_ID=AuditRevisionEntity(id=83, timestamp=Fri Mar 15 07:02:48 UTC 2024, user=null, authType=JWT, authDetails={...}), id=PersonId(value=1213445)}]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [PersonEntity_AUDIT#{REVISION_ID=AuditRevisionEntity(id=83, timestamp=Fri Mar 15 07:02:48 UTC 2024, user=null, authType=JWT, authDetails={...}), id=PersonId(value=1213445)}]
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Getter
// suppress warnings due to Builder and usage of equals/hashcode defined in parent class
@SuppressWarnings({"java:S2160", "JpaObjectClassSignatureInspection"})
@Entity
@Audited
@IdClass(PersonEntityId.class)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class PersonEntity {

    @Id
    PersonId id;
....
}
@NoArgsConstructor
@AllArgsConstructor
public class PersonEntityId implements Serializable {

    private static final long serialVersionUID = ...;

    @Column
    @Convert(converter = PersonIdConverter.class)
    @Getter
    private PersonId id;
}
@Converter(autoApply = true)
public class PersonIdConverter implements AttributeConverter<PersonId, String> {

    @Override
    public String convertToDatabaseColumn(final @Nullable PersonId personId) {
        return Optional.ofNullable(personId).map(PersonId::getValue).orElse(null);
    }

    @Override
    public PersonId convertToEntityAttribute(final @Nullable String id) {
        return PersonId.fromString(id).getOrNull();
    }
}

Hibernate version: 5.4.29.Final

person_audit has PRIMARY KEY (revision_id, id)

I have tried removing id from the primary key, but wasn't successful.

0

There are 0 best solutions below