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.