Search code examples
javers

How can I get the latest shadow of an Entity containing Entities in Javers?


I will continue with the example given by Bartek Walacik here, but add a color property to Cars.

@Entity
class Garage {
    @Id int id
    Set<Car> cars

    String toString() {
        "Garage " +id + "\n"+ cars.collect{it.toString()}
    }
}

@Entity
class Car {
    @Id int id
    String color

    String toString() {
        "Car " +id + " " + color
    }
}

def "should print "(){
  when:
  def javers = JaversBuilder.javers().build()
  def mutatingCar = new Car(id:2, color:"blue")
  javers.commit("", new Garage(id:1, cars: [mutatingCar, new Car(id:3, color:"red")]))

  Shadow<Garage> g = javers.findShadows(
          QueryBuilder.byClass(Garage).withScopeCommitDeep().build())[0]

  then:
  true
  println (g.get())
}

This will output:

Garage 1
[Car 2 blue, Car 3 red]

Now I repaint my car, commit it and print the garage again, but using withScopeDeepPlus:

mutatingCar.color = "green"
javers.commit("", mutatingCar)
Shadow<Garage> g = javers.findShadows(
          QueryBuilder.byClass(Garage).withScopeDeepPlus().build())[0]
println (g.get())

This will give the same output as above, but I would like to have all entities at their latest, giving this output:

Garage 1
[Car 2 green, Car 3 red]

So my question is: Is it possible to get the latest shadow of an entity with its referenced entities also at their latest snapshot?

I understand that this is not a correct historical state, but the option to do this would be nice, since it would remove the need of querying the database in almost any other way.


Solution

  • Interesting question. The quick answer for

    Is it possible to get the latest shadow of an entity with its referenced entities also at their latest shadows?

    is no, there is no such method, but maybe it should be implemented in Javers. Maybe loadLatestShadowGraph()?

    For now, when you get a Shadow of an object, it's a historical view, restored for the commit date of this Shadow root object (in your example, Garage is the Shadow root). All referenced Shadows are loaded for the commit date of the Shadow root.