Search code examples
scalasorm

How do i update a foreign entity?


I can't seem to update the fields within a foreign entity using .copy(..) and Db.save. No exception gets thrown at all and the T with Persisted that gets returned from the method reflects exactly what I attempted to update. However, when I attempt to retrieve the value using Db.query or Db.fetchById, only the non-foreign fields are updated. For example:

case class Foo (a: String)
case class Bar (b: String, barfoo: Foo)
....
....
val foo1 = Db.save(Foo("Hello"))

val bar1 = Db.save(Bar("World", foo1))

val result = Db.save(bar1.copy(b="Beatiful World", 
        barfoo = bar1.barfoo.copy(a = "Hello My")))

println(result) // Prints: Bar(1,Beatiful World,Foo(1,Hello My))

println(Db.fetchById[Bar](result.id)) // Prints: Bar(1,Beatiful World,Foo(1,Hello))

So, as you can see the barfoo field was not updated.

Is this the wrong way to approach updating foreign entities ? or perhaps this is a bug?

I'm using SORM v0.3.12 btw.


Solution

  • This behaviour is by design. You need to explicitly update the inner entity. I.e.:

    Db.save(bar1.barfoo.copy(a = "Hello My"))
    Db.save(bar1.copy(b="Beatiful World"))
    

    Actually on one stage of SORM's development the update of inner records was automatic (meaning that your example would have worked as you expected), but it required a dedicated UPDATE statement which was redundant in cases when the inner entity didn't change. So the decision was made to make it explicit.

    This is still a debatable subject and there is a possibility that future versions will choose a different approach.