在 Kotlin 中使用 Room 的 @ForeignKey 作为 @Entity 参数

2024-04-20

我遇到了一个房间tutorial https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a这利用了@PrimaryKey类定义上的注释:

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

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

@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))顶部也有片段,但我无法编译:

注释不能用作注释参数。

我纳闷:怎么会(我认为是)同样的概念在 Java 中有效,但在 Kotlin 中无效?另外,有没有办法解决这个问题?

欢迎所有意见。


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

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

Since 科特林 1.2 https://kotlinlang.org/docs/reference/whatsnew12.html#array-literals-in-annotations,您还可以使用数组文字:

@Entity(tableName = "Foo",
    foreignKeys = [
        ForeignKey(entity = Bar::class,
                parentColumns = ["someCol"],
                childColumns = ["someOtherCol"],
                onDelete = CASCADE)])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Kotlin 中使用 Room 的 @ForeignKey 作为 @Entity 参数 的相关文章

随机推荐