繁体   English   中英

如何在 r2dbc 中实现多对多

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM