How can I handle hierarchy of nested entities with

2019-08-20 06:47发布

问题:

I am comparing two objects that have nested collections inside of them. The resulting diff has everything I would expect, except for how to reconstruct the hierarchy.

As an illustrative example:

I create a new garage, g1, with two cars, c1 and c2. c1 has 2 seats c1s1, c1s2. c2 has 1 seat, c2s1. My SimpleTextChangeLog looks something like this:

new object: ...Garage/g1
new object: ...Seat/c2s1
new object: ...Car/c2
new object: ...Car/c1
new object: ...Seat/c1s1
new object: ...Seat/c1s2

I would like my implementation of ChangeProcessor to print the change in a hierarchical form:

new object: ...Garage/g1
    new object: ...Car/c1
        new object: ...Seat/c1s1
        new object: ...Seat/c1s2
    new object: ...Car/c2
        new object: ...Seat/c2s1

Class hierarchy:

@entity
class Garage {
    Set<Car> cars; 
    ...
}

@entity
class Car {
    Set<Seat> seats; 
    ...
}

@entity
class Seat {
    ...
}

Is there a way to do this?

回答1:

Change list is a flat, unsorted list, so you can't reproduce hierarchy form changes.

Why not use Shadows?

@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 toString() {
        "Car " +id
    }
}


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

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

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

output:

Garage 1
[Car 2, Car 3]


标签: javers