使用 Spring Data REST 存储库时,如何在保存之前确定 RESTful 资源的哪些属性已更改? [英] How to determine which properties of a RESTful resource have changed before save when using Spring Data REST repositories?

查看:24
本文介绍了使用 Spring Data REST 存储库时,如何在保存之前确定 RESTful 资源的哪些属性已更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有 Spring Data REST 发布的以下资源...

If I have the following resource published by Spring Data REST...

{ "status": "idle" }

对于更改属性 status 的值的 PATCH 或 PUT,我该如何反应?这个想法是根据属性更改触发一些服务器进程.

How could I react to a PATCH or PUT that changes the value of property status? The idea would be to trigger some server process based on a property change.

理想情况下,这会在保存之前发生,并且可以将资源的新版本与先前保留的版本进行比较.

Ideally this would happen before save and it would be possible to compare the new version of the resource with the previously-persisted version.

推荐答案

您通常会使用 @RepositoryEventHandler 来连接您的事件逻辑 - 请参阅 文档了解详情.

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

我不知道有什么函数可以直接获取更改后的属性.但是,如果您使用 HandleBeforeSave 处理程序,您可以加载持久实体(旧状态)并将其与新状态进行比较 -

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
        }
       }
    }

请注意,您需要将 newPerson 从当前 EntityManager 中分离出来.否则,我们将在调用 findOne 时获取缓存的 person 对象 - 我们无法根据当前数据库状态与更新版本进行比较.

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.

如果使用 Eclipselink 的替代方案

如果您正在使用 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();

        }

这篇关于使用 Spring Data REST 存储库时,如何在保存之前确定 RESTful 资源的哪些属性已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆