【问题标题】:How to set cascade type in a One-To-Many relationship in Kotlin Exposed?如何在 Kotlin Exposed 的一对多关系中设置级联类型?
【发布时间】:2019-05-03 01:06:42
【问题描述】:

我有两个处于一对多关系的实体。 “One”实体拥有“Many”的生命周期。如果删除“One”实体,我希望自动删除属于“One”的所有“Many”实体。

我假设有一种方法可以像在 Hibernate 中一样将引用设置为“CascadeType.DELETE”,因此我不必在删除“One”之前删除所有“Many”。

object Apis : IntIdTable() {
    val name = varchar("name", 20)
    val url = varchar("url", 255)
    val method = enumerationByName("method", 20, HttpMethod::class)
    val requestBody = varchar("request_body", 65535)
    val responseDsl = varchar("response_dsl", 65535)
    val responseType = enumerationByName("response_type", 20, ResponseType::class)
    val enabled = bool("enabled")
}

class Api(id: EntityID<Int>) : IntEntity(id){
    companion object : IntEntityClass<Api>(Apis)

    var name by Apis.name
    var url by Apis.url
    var method by Apis.method
    var requestBody by Apis.requestBody
    var responseDsl by Apis.responseDsl
    var responseType by Apis.responseType
    var enabled by Apis.enabled
    val headers by ApiHeader referrersOn ApiHeaders.id
}

object ApiHeaders : IdTable<Int>() {
    override val id = reference("api_id", Apis).primaryKey()
    val key = varchar("key", 255)
    val value = varchar("value", 255)
}

class ApiHeader(id: EntityID<Int>) : Entity<Int>(id) {
    companion object : EntityClass<Int, ApiHeader>(ApiHeaders)

    var api by Api referencedOn ApiHeaders.id
    var key by ApiHeaders.key
    var value by ApiHeaders.value
}

fun main() {
    transaction {
        addLogger(StdOutSqlLogger)
        val api = Api.findById(1)
        // if headers are not deleted, api can't be deleted directly
        api?.headers?.forEach { it.delete() }
        api?.delete()
        commit()
    }
}

我需要一种方法来轻松设置所需的级联关系类型。

【问题讨论】:

    标签: kotlin-exposed


    【解决方案1】:

    reference()optReference() 函数具有可选参数:onUpdate 和 onDelete。

    在你的情况下,你必须写:

    object ApiHeaders : IdTable<Int>() {
        override val id = reference("api_id", Apis, onDelete = ReferenceOption.CASCADE).primaryKey()
        val key = varchar("key", 255)
        val value = varchar("value", 255)
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多