在Kotlin中使用Room的@ForeignKey作为@Entity参数 [英] Using Room's @ForeignKey as @Entity parameter in Kotlin

查看:2289
本文介绍了在Kotlin中使用Room的@ForeignKey作为@Entity参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个教程的房间,类定义上的 @PrimaryKey 注释:

I came across a Room tutorial that makes use of the @PrimaryKey annotation on the class definition:

@Entity(foreignKeys = @ForeignKey(entity = User.class,
                              parentColumns = "id",
                              childColumns = "userId",
                              onDelete = CASCADE))
public class Repo {
    ...
}

现在,我有以下想要使用的数据类主键上:

Now, I have the following data class that want to use a primary key on:

@Parcel(Parcel.Serialization.BEAN) 
data class Foo @ParcelConstructor constructor(var stringOne: String,
                                              var stringTwo: String,
                                              var stringThree: String): BaseFoo() {

    ...
}

所以,我刚刚添加了 @Entity(tableName =Foo,foreignKeys = @ForeignKey(entity = Bar :: class,parentColumns =someCol,childColumns =someOtherCol,onDelete = CASCADE))顶部的代码段,但我无法编译:

So, I just added the @Entity(tableName = "Foo", foreignKeys = @ForeignKey(entity = Bar::class, parentColumns = "someCol", childColumns = "someOtherCol", onDelete = CASCADE)) snippet on the top as well, but I can't compile:


注释可以' t用作注释参数。

An annotation can't be used as the annotations argument.

我想知道:怎么来(我认为是)同样的概念在Java中工作但在Kotlin中没有?另外,有没有办法解决这个问题?

I wonder: how come (what I think is) the same concept working in Java but not in Kotlin? Also, is there a way to go around this?

欢迎所有输入。

推荐答案

这是提供您正在寻找的注释的方法,使用显式的参数数组,并且没有 @ 用于嵌套注释的创建: / p>

This is the way to provide the annotation you're looking for, with explicit arrays for the arguments, and no @ for the nested annotation's creation:

@Entity(tableName = "Foo", 
    foreignKeys = arrayOf(
            ForeignKey(entity = Bar::class, 
                    parentColumns = arrayOf("someCol"), 
                    childColumns = arrayOf("someOtherCol"), 
                    onDelete = CASCADE)))

由于 Kotlin 1.2 ,你也可以使用数组文字:

Since Kotlin 1.2, you can also use array literals:

@Entity(tableName = "Foo",
    foreignKeys = [
        ForeignKey(entity = Bar::class,
                parentColumns = ["someCol"],
                childColumns = ["someOtherCol"],
                onDelete = CASCADE)])

这篇关于在Kotlin中使用Room的@ForeignKey作为@Entity参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆