NULL ID Generated Via @GeneratedValue On Composite Key Using @EmbeddedId

后端 未结 1 644
花落未央
花落未央 2021-01-13 00:09

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

1条回答
  •  醉梦人生
    2021-01-13 00:28

    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:

    1. Use an @Version annotated field and leave this uninitialized before the first call to save(…).
    2. Implement 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).

    0 讨论(0)
提交回复
热议问题