Example with Spring Data JPA

Learn how to implement a persistence adapter with the help of an example in Spring Data JPA.

The Account data class

Let’s look at a code example that implements the AccountPersistenceAdapter from the figures in the previous lessons. This adapter will have to save and load accounts to and from the database. We have already seen the Account entity in chapter “Implementing a Use Case”, but here is its skeleton again for reference:

Press + to interact
package buckpal.account.domain;
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Account {
@Getter private final AccountId id;
@Getter private final ActivityWindow activityWindow;
private final Money baselineBalance;
public static Account withoutId(
Money baselineBalance,
ActivityWindow activityWindow) {
return new Account(null, baselineBalance, activityWindow);
}
public static Account withId(
AccountId accountId,
Money baselineBalance,
ActivityWindow activityWindow) {
return new Account(accountId, baselineBalance, activityWindow);
}
public Money calculateBalance() {
// ...
}
public boolean withdraw(Money money, AccountId targetAccountId) {
// ...
}
public boolean deposit(Money money, AccountId sourceAccountId) {
// ...
}
}

Note that the Account class is not a simple data class with getters and setters but instead, tries to be as immutable as possible. It only provides factory methods that create an Account in a valid state, and all mutating methods do some validation, like checking the account balance before withdrawing money, so that we cannot create an invalid domain model.

The AccountJpaEntity class

We’ll use Spring Data JPAJava Persistence API to talk to the database, so we ...