javers / javers

JaVers - object auditing and diff framework for Java
http://javers.org
Apache License 2.0
1.39k stars 361 forks source link

Referencing snapshots in entity model #1166

Open raouf-g opened 2 years ago

raouf-g commented 2 years ago

Is your feature request related to a problem? Please describe. I have a model consisting of a Product and Purchase. When the purchase is done it has to be associated to the actual version of the product which will give a history to the customer about the product description and price.

Describe the solution you'd like It would be very convenient if an annotation @Snapshot exist to decorate a property in the entity model, So when it's persisted it will write the current @Version along with the @Id, and when when it's read it will bring the entity's Shadow.

Describe alternatives you've considered Using javers-spring-boot-starter-mongo (simplified code)

@Component
public class MongoShadowListener extends AbstractMongoEventListener<Object> {

    @Autowired
    Javers javers;

    @Override
    public void onBeforeSave(BeforeSaveEvent<Object> event) {
       Arrays.stream(FieldUtils.getFieldsWithAnnotation(event.getSource().getClass(), Snapshot.class))
                .forEach(field -> event.getDocument().put(field.getName(), 
                           snapshotToDBRef(javers.findOrCreateSnapshot(event.getSource()))));
    }

    @Override
    public void onAfterConvert(AfterConvertEvent<Object> event) {
        Arrays.stream(FieldUtils.getFieldsWithAnnotation(source.getClass(), Snapshot.class))
                .forEach(field -> FieldUtils.writeField(field, event.getSource(), 
                     javers.findShadows(QueryBuilder.byInstanceId(...).withCommitId(...)).findFirst()));
    }
}

Additional context The purchase collection will look like: image

bartoszwalacik commented 2 years ago

@raouf-g interesting idea. Could you please provide a complete design with code snippets? I mean how you see it form a Javers' user perspective. Could be a failing E2E test case