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

标签 java android kotlin android-room java-annotations

我遇到了一个房间 tutorial在类定义中使用 @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)) 代码 fragment 也在顶部,但我无法编译:

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

我想知道:(我认为是)为什么相同的概念在 Java 中起作用,但在 Kotlin 中却不起作用?另外,有没有办法解决这个问题?

欢迎所有输入。

最佳答案

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

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

自从 Kotlin 1.2 ,你也可以使用数组字面量:

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

关于java - 在 Kotlin 中使用 Room 的 @ForeignKey 作为 @Entity 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414476/

相关文章:

android - 如何在 Android Compose TextField 的虚拟键盘上启用大写?

Kotlin 协程流程 : How to get the first item from a flow (i.文件元数据)并将其余项目作为内容流传递?

kotlin - 如果不推荐使用 `when (a) in x..y`,我应该使用什么呢?

java - 桌面 SWING 应用程序上的 jpa

android - 后退按钮显示空白屏幕

java - 使用 Spring Security 和 AngularJS 预防 CSRF

android - 从 Android Studio 中完全删除一个项目?

android - 如何从命令行构建android apk?

java - Eclipse 环境中的 Hadoop

java - Solr:结合 EdgeNGramFilterFactory 和 NGramFilterFactory