Spring Data Rest:跟踪历史表中的数据更改

时间:2014-09-17 06:03:20

标签: java spring spring-data spring-data-rest

我想使用Spring Data Rest跟踪历史表中对数据的更改。我的预期行为是,对于每个更改数据的事务,一个条目会自动添加到我的历史记录表中。我不确定,但我不认为在使用服务时跨越多个请求的事务是有效的。

我目前有两种选择:

1)对数据使用数据库触发器 - 我在这里看到的缺点是,目前我们的大部分操作都是通过Java完成的,我没有看到任何方法通过Java实现这一点。

2)使用Annotated事件处理程序 - 我们将为每个表创建事件处理程序,以跟踪历史记录,我倾向于这样做,但我不确定这是否是正确的方法。

两个选项中哪一个更好?还有其他选择吗?

3 个答案:

答案 0 :(得分:2)

使用Spring Data Rest,您可以选择使用events进行任何前后处理。我相信原始事务边界适用于这些事件中的任何数据库操作。

答案 1 :(得分:0)

我知道我这几年后才回答,但这是另一种方法:

创建RepositoryEventHandler

@Component
@RepositoryEventHandler(Code.class)
public class CodesEventHandler {

    @Autowired
    private CodesRepository repository;

    @HandleBeforeSave
    public void handleBeforeSave(Code c) {
        // backup the existing data to history (happens to be on the same table)
        Code newC = new Code();
        BeanUtils.copyProperties(c, newC);
        CodeId newId = new CodeId();
        BeanUtils.copyProperties(c.getCodeId(), newId);
        newC.setCodeId(newId);
        Date now = new Date();
        newC.getCodeId().setValidToTs(now);
        repository.save(newC);

        c.setValidFromTs(now);

    }

    @HandleBeforeDelete
    public void handleBeforeDelete(Code c) {
        // same as above but this time set the end timestamp to be now
    }
}

答案 2 :(得分:0)

使用Envers审核操作official site