在没有更改的提交后获取返回的提交

Getting a Commit returned after a commit with no changes

如果我两次提交同一个实体,第一次有更改,第二次没有任何更改,我两次都会收到带有 CommitId 的 Commit。第一个包含更改,第二个有一个空的更改列表。

这种行为是故意的吗?我希望第二次提交不会获得 CommitId,因为数据库中没有更改也没有提交。我通过检查更改列表是否为空来解决了这个问题。

我的存储库

public class CustomerRepository {

    private final Javers javers;

    CustomerRepository(Javers javers) {
        this.javers = javers;
    }

    public Optional<CommitId> save(Customer customer, Metadata metadata) {
        try {
            var author = Optional.ofNullable(metadata.author())
                    .orElse("unknown");

            Commit commit = javers.commit(author, customer); //<-- this returns a Commit with a CommitId

            return Optional.of(commit.getId());
        } catch (Exception exception) {
            log.warn("Couldn't commit customer", exception);
        }
        return Optional.empty();
    }

    public ChangesByCommit getCommitForCustomer(CustomerId customerId, CommitId commitId) {
        var query = QueryBuilder
                .byInstanceId(customerId.getValue(), Customer.class)
                .withCommitId(commitId)
                .withChildValueObjects()
                .build();
        return javers.findChanges(query).groupByCommit().stream().findFirst().orElseThrow(() -> new CommitNotFoundException(customerId, commitId));
    }
}

我的测试用例是这样的

    @Test
    void emptyCommit() {
        var customer = new Customer(new CustomerId("id"));
        var metadata = new Metadata("author");
        Optional<CommitId> initialCommit = repository.save(customer, metadata);

        assertThat(initialerCommit).isPresent();

        customer.addDeliveryAddressToAddressBookList(new DeliveryAddress("name", "surname", "street", "city"));

        Optional<CommitId> commitWithChanges = repository.save(customer, metadata);
        Optional<CommitId> commitWithoutChanges = repository.save(customer, metadata);

        assertThat(commitWithChanges).isPresent();
        assertThat(commitWithoutChanges).isPresent();

        ChangesByCommit initialChanges = repository.getCommitForCustomer(new CustomerId(customer.getId()), initialCommit.get());
        ChangesByCommit addedAddressBookChanges = repository.getCommitForCustomer(new CustomerId(customer.getId()), commitWithChanges.get());
        assertThrows(CommitNotFoundException.class, () ->  repository.getCommitForCustomer(new CustomerId(customer.getId()), commitWithoutChanges.get()));
    }

这就是 Javers 的工作方式,你可以有空提交(没有快照),但你不能没有提交。这种设计在 Javers API 中表示,当您调用 javers.commit() 时,您会得到一个 Commit 对象而不是 Optional<Commit>