Persist coffee order
Description¶
In this lab, we'll store the coffee orders and their items in an in-memory H2 database.
Update the pom.xml
For this lab, you'll need the Spring Data support.
Go into the pom.xml
and uncomment the dependencies under "Database dependencies"
and refresh the Maven file.
a. JPA Classes¶
-
Create a new package
com.welltestedlearning.coffeekiosk.adapter.out.jpa
-
Into that package copy the CoffeeItemEntity.java, CoffeeOrderEntity.java, and CoffeeOrderJpaRepository.java
b. Create Adapter¶
-
Create a new class
CoffeeOrderJpaAdapter
that implements theCoffeeOrderRepository
and is annotated with@Repository
. This follows the adapter design pattern, adapting the domain repository methods to the JPA repository.Conflicting Implementations
Since now this class and the
InMemoryCoffeeOrderRepository
conflict, you need to further annotate this class to tell Spring which one to use.You can annotate this class with
@Primary
, which tells Spring that this is the preferred implementation.You can also use the
@Profile
annotation on this class as well as on the@Bean
annotation in theCoffeeOrderRepositoryConfig
class. -
Autowire the
CoffeeOrderJpaRepository
into the constructor and store it in an instance field. -
You should be able to start the application with no errors, though it won't yet work.
-
For the
findById
method, you will call the JPA repository'sfindById
method and use theOptional
'smap
function to transform it to a domain object.Example with UserProfile
This is an example for a
UserProfile
:public Optional<UserProfile> findById(Long profileId) { Optional<UserProfileEntity> entity = userProfileJpaRepository.findById(profileId); return entity.map(UserProfileEntity::toDomain); }
-
The
findAll
is similar, using themap
function on thestream()
Example with UserProfile
This is an example for a
UserProfile
:public List<UserProfile> findAll() { return userProfileJpaRepository.findAll() .stream() .map(UserProfileEntity::toDomain) .collect(Collectors.toList()); }
-
The
save
works in the other direction, using the staticCoffeeOrderEntity.domainToEntity
method.Example with UserProfile
This is an example for a
UserProfile
:public UserProfile save(UserProfile userProfile) { UserProfileEntity entity = UserProfileEntity.domainToEntity(userProfile); entity = userProfileJpaRepository.save(entity); return entity.toDomain(); }
c. Try It Out¶
Start the application and try it out.