Trying to save a row in a table that has a composite key (Long & Date) via Spring Data JPA. The Long part of the composite key is @GeneratedValue. But I\'m getting the f
It looks like you're setting the ID value to half-prepared state (Date
being set but the long
field to be initialized by the persistence provider, right? This means, pk
is effectively non-null
when the CashBatchPaymentHistoryDto
instance is handed to repository.save(…)
. If so, this will cause an EntityManager.merge(…)
being triggered, which can imagine to cause the exception as it's not going to expect to have to generate ids.
Generally speaking, if you're manually maintaining id values (even only partial ones), you have to explicitly determine the is-new-state of the entity (as this will effectively decide whether to call persist(…)
or merge(…)
in the JPA case). By default, this works by looking at the id field and interpreting a null
value as new, non-null
as not new.
In your current situation there are two options:
@Version
annotated field and leave this uninitialized before the first call to save(…)
.Persistable
and its isNew()
method to inspect your objects state to correctly decide whether it's new or not (in your case probably by checking (pk.cashBatchID
for being null
).