跳到主要内容
版本:4.1.1

用法

Doubao 中英对照 Usage

现在您可以使用 RevisionRepository 中的方法来查询实体的修订,如下例测试用例所示:

@ExtendWith(SpringExtension.class)
@Import(EnversDemoConfiguration.class) 1
class EnversIntegrationTests {

final PersonRepository repository;
final TransactionTemplate tx;

EnversIntegrationTests(@Autowired PersonRepository repository, @Autowired PlatformTransactionManager tm) {
this.repository = repository;
this.tx = new TransactionTemplate(tm);
}

@Test
void testRepository() {

Person updated = preparePersonHistory();

Revisions<Long, Person> revisions = repository.findRevisions(updated.id);

Iterator<Revision<Long, Person>> revisionIterator = revisions.iterator();

checkNextRevision(revisionIterator, "John", RevisionType.INSERT);
checkNextRevision(revisionIterator, "Jonny", RevisionType.UPDATE);
checkNextRevision(revisionIterator, null, RevisionType.DELETE);
assertThat(revisionIterator.hasNext()).isFalse();

}

/**
* Checks that the next element in the iterator is a Revision entry referencing a Person
* with the given name after whatever change brought that Revision into existence.
* <p>
* As a side effect the Iterator gets advanced by one element.
*
* @param revisionIterator the iterator to be tested.
* @param name the expected name of the Person referenced by the Revision.
* @param revisionType the type of the revision denoting if it represents an insert, update or delete.
*/
private void checkNextRevision(Iterator<Revision<Long, Person>> revisionIterator, String name,
RevisionType revisionType) {

assertThat(revisionIterator.hasNext()).isTrue();
Revision<Long, Person> revision = revisionIterator.next();
assertThat(revision.getEntity().name).isEqualTo(name);
assertThat(revision.getMetadata().getRevisionType()).isEqualTo(revisionType);
}

/**
* Creates a Person with a couple of changes so it has a non-trivial revision history.
* @return the created Person.
*/
private Person preparePersonHistory() {

Person john = new Person();
john.setName("John");

// create
Person saved = tx.execute(__ -> repository.save(john));
assertThat(saved).isNotNull();

saved.setName("Jonny");

// update
Person updated = tx.execute(__ -> repository.save(saved));
assertThat(updated).isNotNull();

// delete
tx.executeWithoutResult(__ -> repository.delete(updated));
return updated;
}
}
  • 这里引用的是前面(配置一节中)给出的应用程序上下文配置。

延伸阅读​

您可以下载 Spring Data Examples 仓库中的 Spring Data Envers 示例并动手试用,以感受该库的工作方式。

您还应查阅 RevisionRepository 的 Javadoc及相关类。

Spring Data Envers 的源代码和问题跟踪器托管在 GitHub 上(作为 Spring Data JPA 的一个模块)。