Example with Spring Data JPA
Explore how to implement a persistence adapter with Spring Data JPA by mapping domain entities to database models. Understand CRUD operations, repository usage, and the importance of maintaining a clean domain model separate from persistence concerns for better flexibility and testability.
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:
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