I have two entities with One-to-one
association between them. chatId
from MetaDataEntity
is the value of column id
from ChatEntity
.
But there is a problem when I try to create ChatEntity
. In this case I get an exception that chatId
for MetaDataEntity
canon be nullable. How can I solve it? Is it possible to save these two entities during one request like chatRepository.save(chatEntity)
to database?
@Entity
@Table(name = "chat")
data class ChatEntity(
val name: String?,
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id", referencedColumnName = "chatId")
val metaData: MetaDataEntity? = null
) {
@Id
@GeneratedValue
var id: UUID? = null
}
@Entity
@Table(name = "meta_data")
data class MetaDataEntity(
@Id
val chatId: UUID,
val lastBumpingActivityAt: Instant?,
)
CREATE TABLE _chat_meta_data
(
chat_id uuid NOT NULL CONSTRAINT _chat_meta_data_pkey PRIMARY KEY,
last_bumping_activity_at timestamp
);
I have two entities with One-to-one
association between them. chatId
from MetaDataEntity
is the value of column id
from ChatEntity
.
But there is a problem when I try to create ChatEntity
. In this case I get an exception that chatId
for MetaDataEntity
canon be nullable. How can I solve it? Is it possible to save these two entities during one request like chatRepository.save(chatEntity)
to database?
@Entity
@Table(name = "chat")
data class ChatEntity(
val name: String?,
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id", referencedColumnName = "chatId")
val metaData: MetaDataEntity? = null
) {
@Id
@GeneratedValue
var id: UUID? = null
}
@Entity
@Table(name = "meta_data")
data class MetaDataEntity(
@Id
val chatId: UUID,
val lastBumpingActivityAt: Instant?,
)
CREATE TABLE _chat_meta_data
(
chat_id uuid NOT NULL CONSTRAINT _chat_meta_data_pkey PRIMARY KEY,
last_bumping_activity_at timestamp
);
Share
Improve this question
asked Mar 10 at 15:01
NeverSleepsNeverSleeps
1,9602 gold badges27 silver badges49 bronze badges
1 Answer
Reset to default 1Use 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.