Spring data 弹簧&x2B;Google数据存储:@引用未持久化

Spring data 弹簧&x2B;Google数据存储:@引用未持久化,spring-data,google-cloud-datastore,spring-cloud,Spring Data,Google Cloud Datastore,Spring Cloud,我正在与Kotlin一起使用org.springframework.cloud:springcloud gcp starter数据存储 代码如下所示: @Entity(name = "books") data class Book( @Reference val writer: Writer, var name: String, @Id val id: Key? = null, //I leave the key as NULL so it that can be aut

我正在与Kotlin一起使用
org.springframework.cloud:springcloud gcp starter数据存储

代码如下所示:

@Entity(name = "books")
data class Book(
    @Reference val writer: Writer,
    var name: String,
    @Id val id: Key? = null, //I leave the key as NULL so it that can be autogenerated
)

@Entity(name = "writers")
data class Writer(
    var name: String,
    @Id val id: Key? = null
)

//Also with Repositories
@Entity(name = "books")
data class Book(
    @Reference var writer: Writer?, //Accepting NULL values
    var name: String,
    @Id val id: Key? = null
)
当我保存一个书实体时,引用一个保存的编写器,当我检索它时,应该自动检索它,对吗

示例代码:

var w = Writer("Shakespeare")
w = writerRepo.save(w)
var book = Book(w, "Macbeth")
book = bookRepo.save(book)

books = bookRepo.findByWriter(w) //Error happen here

上面的代码将抛出一个错误:无法用空Writer实例化Book。知道为什么会发生这种情况吗?

我发现答案不是因为关系没有持久化,而是因为存储库在实例化之后设置了关系实体。存储库首先尝试实例化实体,在关系(用@References注释)属性上分配NULL

因此,实体应如下所示:

@Entity(name = "books")
data class Book(
    @Reference val writer: Writer,
    var name: String,
    @Id val id: Key? = null, //I leave the key as NULL so it that can be autogenerated
)

@Entity(name = "writers")
data class Writer(
    var name: String,
    @Id val id: Key? = null
)

//Also with Repositories
@Entity(name = "books")
data class Book(
    @Reference var writer: Writer?, //Accepting NULL values
    var name: String,
    @Id val id: Key? = null
)

所有这些都很好。

我发现答案不是因为关系没有持久化,而是因为存储库在实例化之后设置了关系实体。存储库首先尝试实例化实体,在关系(用@References注释)属性上分配NULL

因此,实体应如下所示:

@Entity(name = "books")
data class Book(
    @Reference val writer: Writer,
    var name: String,
    @Id val id: Key? = null, //I leave the key as NULL so it that can be autogenerated
)

@Entity(name = "writers")
data class Writer(
    var name: String,
    @Id val id: Key? = null
)

//Also with Repositories
@Entity(name = "books")
data class Book(
    @Reference var writer: Writer?, //Accepting NULL values
    var name: String,
    @Id val id: Key? = null
)
一切都很好