我在Kotlin中使用org.springframework.cloud:spring-cloud-gcp-starter-data-datastore
。
代码看起来像这样:
@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
[当我保存Book实体并引用一个已保存的Writer时,当我检索它时,应该自动检索它对吗?
示例代码:
var w = Writer("Shakespeare")
w = writerRepo.save(w)
var book = Book(w, "Macbeth")
book = bookRepo.save(book)
books = bookRepo.findByWriter(w) //Error happen here
上面的代码将引发错误,无法使用NULL Writer实例化Book。知道为什么会这样吗?
我发现答案不是因为关系没有持久,而是因为存储库在实例化之后设置了关系实体。存储库尝试首先实例化Entity,在关系(用@References注释)属性上分配NULL。
因此,实体应该像这样:
@Entity(name = "books")
data class Book(
@Reference var writer: Writer?, //Accepting NULL values
var name: String,
@Id val id: Key? = null
)
而且一切正常。