Skip to content

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

  1. Create a new package com.welltestedlearning.coffeekiosk.adapter.out.jpa

  2. Into that package copy the CoffeeItemEntity.java, CoffeeOrderEntity.java, and CoffeeOrderJpaRepository.java

b. Create Adapter

  1. Create a new class CoffeeOrderJpaAdapter that implements the CoffeeOrderRepository 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 the CoffeeOrderRepositoryConfig class.

  2. Autowire the CoffeeOrderJpaRepository into the constructor and store it in an instance field.

  3. You should be able to start the application with no errors, though it won't yet work.

  4. For the findById method, you will call the JPA repository's findById method and use the Optional's map 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);
    }
    
  5. The findAll is similar, using the map function on the stream()

    Example with UserProfile

    This is an example for a UserProfile:

    public List<UserProfile> findAll() {
      return userProfileJpaRepository.findAll()
                                     .stream()
                                     .map(UserProfileEntity::toDomain)
                                     .collect(Collectors.toList());
    }
    
  6. The save works in the other direction, using the static CoffeeOrderEntity.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.