[英]How to implement ManyToMany in r2dbc
R2DBC 目前不支持復合鍵。 我想知道我們現在如何實現多對多關系?
例如,給定兩個實體:
@Table
class Item(
@Id var id: Long?,
var title: String,
var description: String,
)
@Table
class Tag(
@Id
var id: Long?,
var title: String,
var color: String,
)
及其架構:
CREATE TABLE item (
id SERIAL PRIMARY KEY NOT NULL,
title varchar(100) NOT NULL,
description varchar(500) NOT NULL
);
CREATE TABLE tag (
id SERIAL PRIMARY KEY NOT NULL,
title varchar(100) NOT NULL,
color varchar(6) NOT NULL
);
我可以為多對多映射創建一個表:
CREATE TABLE item_tag (
item_id bigint NOT NULL,
tag_id bigint NOT NULL,
PRIMARY KEY(item_id, tag_id)
);
但是我們應該如何在 kotlin/java 中定義映射 class ItemTag
呢?
@Table
class ItemTag(
// ??????????????????????? @Id ?????????????????????
var itemId: Long,
var tagId: Long,
)
還是可以省略@Id
? 那么 class 不能有任何Repository
嗎? 我想那會很好。 這是唯一的暗示嗎?
可能還有其他方法可以做到這一點。 由於我認為R2DBC
中尚不支持CompositeKey
。 因此,這只是解決您的問題的一種方法。
數據 class
data class ItemTag(val itemId: Long, val tagId: Long)
然后存儲庫
interface TagRepository {
fun getItemTagByTagId(tagId: Long): Flow<ItemTag>
}
存儲庫實現
@Repository
class TagRepositoryImpl(private val databaseClient: DatabaseClient) : TagRepository {
override fun getItemTagByTagId(tagId: Long): Flow<ItemTag> {
return databaseClient.sql("SELECT * FROM item_tag WHERE tag_id = :tagId")
.bind("tagId", tagId)
.map(row, _ -> rowToItemTag(row))
.all()
.flow()
}
private fun rowToItemTag(row: Row): ItemTag {
return ItemTag(row.get("item_id", Long::class.java)!!, row.get("tag_id", Long::class.java)!!)
}
}
類似的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.