79498667

Date: 2025-03-10 17:05:16
Score: 1
Natty:
Report link

Use a shared primary key. In your MetaDataEntity, annotate the ChatEntity relationship with @MapsId so that it reuses ChatEntity’s generated ID. With cascading enabled, saving ChatEntity will persist both entities in one request.

Example:

@Entity
data class ChatEntity(
    val name: String?,
    @OneToOne(mappedBy = "chat", cascade = [CascadeType.ALL], orphanRemoval = true)
    var metaData: MetaDataEntity? = null
) {
    @Id @GeneratedValue
    var id: UUID? = null
}

@Entity
data class MetaDataEntity(
    @Id
    var chatId: UUID? = null,
    @OneToOne
    @MapsId
    @JoinColumn(name = "chat_id")
    var chat: ChatEntity,
    val lastBumpingActivityAt: Instant?
)

Now, saving ChatEntity (with metaData set) will automatically persist MetaDataEntity with the correct ID.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @MapsId
  • Low reputation (1):
Posted by: Walid Salame