Reputation: 4085
I'm using org.springframework.cloud:spring-cloud-gcp-starter-data-datastore
with Kotlin.
The code look like this:
@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
When I save a Book entity, with a reference to a saved Writer, when I retrieve it, it should be retrieved automatically right?
Sample code:
var w = Writer("Shakespeare")
w = writerRepo.save(w)
var book = Book(w, "Macbeth")
book = bookRepo.save(book)
books = bookRepo.findByWriter(w) //Error happen here
The code above will throw error failed to instantiate Book with NULL Writer. Any idea why this happen?
Upvotes: 0
Views: 300
Reputation: 4085
I find the answer is not because the relationship is not persisted but because The Repository set the relationship Entity after instantiation. The Repository tries to instantiate the Entity first, assign NULL on relationship (annotated with @References) attribute.
Therefore, the Entity should be like this:
@Entity(name = "books")
data class Book(
@Reference var writer: Writer?, //Accepting NULL values
var name: String,
@Id val id: Key? = null
)
And all works well.
Upvotes: 2