[英]How to implement ManyToMany in r2dbc
R2DBC does not support composite keys currently. R2DBC 目前不支持复合键。 I wonder how we may implement a many-to-many relationship for now?我想知道我们现在如何实现多对多关系?
For example, given the two entities:例如,给定两个实体:
@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,
)
and their schemas:及其架构:
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
);
I can create a table for the many-to-many mapping:我可以为多对多映射创建一个表:
CREATE TABLE item_tag (
item_id bigint NOT NULL,
tag_id bigint NOT NULL,
PRIMARY KEY(item_id, tag_id)
);
But how should we define the mapping class ItemTag
in kotlin/java?但是我们应该如何在 kotlin/java 中定义映射 class ItemTag
呢?
@Table
class ItemTag(
// ??????????????????????? @Id ?????????????????????
var itemId: Long,
var tagId: Long,
)
Or is it fine to omit the @Id
?还是可以省略@Id
? Then there cannot be any Repository
for the class?那么 class 不能有任何Repository
吗? I guess that would be fine.我想那会很好。 Is this the only implication?这是唯一的暗示吗?
There might be other ways to do this.可能还有其他方法可以做到这一点。 Since CompositeKey
is not supported yet in R2DBC
I think.由于我认为R2DBC
中尚不支持CompositeKey
。 Hence, this is just one way to resolve your problem.因此,这只是解决您的问题的一种方法。
Data class数据 class
data class ItemTag(val itemId: Long, val tagId: Long)
Then Repository然后存储库
interface TagRepository {
fun getItemTagByTagId(tagId: Long): Flow<ItemTag>
}
Repostory Impl存储库实现
@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)!!)
}
}
Something like that.类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.