How to determine which properties of a RESTful resource have changed before save when using Spring Data REST repositories?

本小妞迷上赌 提交于 2019-12-05 20:11:10

You would usually use a @RepositoryEventHandler to hook up your event logic - see the documentation for details.

I do not know of a function to directly get the changed properties. But if you use a HandleBeforeSave handler you can load the persistent entity (old state) and compare it against the new state -

    @RepositoryEventHandler 
    @Component
    public class PersonEventHandler {

      ...

      @PersistenceContext
      private EntityManager entityManager;

      @HandleBeforeSave
      public void handlePersonSave(Person newPerson) {
        entityManager.detach(newPerson);
Person currentPerson = personRepository.findOne(newPerson.getId());
        if (!newPerson.getName().equals(currentPerson.getName)) {
          //react on name change
        }
       }
    }

Note that you need to detach the newPerson from the current EntityManager. Otherwise we would get the cached person object when calling findOne - and we could not compare to the updated version against the current database state.

Alternative if using Eclipselink

If you are using eclipselink you can also find out the changes that have been applied to your entity in a more efficient fashion avoiding the reload - see here for details

        UnitOfWorkChangeSet changes = entityManager.unwrap(UnitOfWork.class).getCurrentChanges();
        ObjectChangeSet objectChanges = changes.getObjectChangeSetForClone(newPerson);
        List<String> changedAttributeNames = objectChanges.getChangedAttributeNames();
        if (objectChanges.hasChangeFor("name")) {
            ChangeRecord changeRecordForName = objectChanges.getChangesForAttributeNamed("name");
            String oldValue = changeRecordForName.getOldValue();

        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!