代码之家  ›  专栏  ›  技术社区  ›  Yosi Pramajaya

Spring+Google数据存储:@引用未持久化

  •  0
  • Yosi Pramajaya  · 技术社区  · 6 年前

    我在用 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
    

    当我保存一个图书实体时,引用一个已保存的作者,当我检索它时,应该自动检索它,对吗?

    示例代码:

    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。知道为什么会这样吗?

    0 回复  |  直到 6 年前
        1
  •  2
  •   Yosi Pramajaya    6 年前

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

    因此,实体应该是这样的:

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

    一切都很顺利。