Skip to main content

Updated for Fall 2026

We’ll start our backend implementation and testing by reviewing some of the fundamentals of Relational Databases and, in particular, how they work with Hibernate and how you can actually use them. For a refresher on what Hibernate is, and why we use it, see the background material under the Hibernate section of the OBP. Today, however, we’ll cover in more detail how databases actually store data and how we can build up increasingly complex data structures (just like you’ve already seen with composing objects together in Java).

Make sure your local MySQL server is running!

Persistence

Persistence Background

We will be talking about relational databases, which you most commonly interact with by writing SQL queries.

Fundamentally, relational databases store data in tables, which are, at a high-level view, very much like tables that you’re familiar with from spreadsheet software such as Excel. That is, each table has a set of columns, which have a name and a type, and rows, which have concrete values corresponding to the actual entities (or records) that get saved into the table. As explained in the linked background above, Hibernate automatically takes care of creating these tables based on our Java classes and then creating rows in the table from actual objects that we are working with.

Consequently, if we define a class such as:

@Entity
@Table(name = "recipes")
public class Recipe {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private int id;
   private String name;
   private int price;
   private int coffee;
   private int milk;
   private int chocolate;
   private int sugar;
}

then Hibernate will create a table that looks something like this:

id (int) name (varchar) price (int) coffee (int) milk (int) chocolate (int) sugar (int)
actual values would go here and here

(note that the actual types would not be shown when looking at the table like this, but they are included here to help clarify that yes, each column has a type)

Further imagine that we have two recipes, as shown below, that we wanted to save into the table:

  • Recipe(id=1,name=Black Coffee,price=1,coffee=1,milk=0,chocolate=0,sugar=0)
  • Recipe(id=2,name=Mocha,price=3,coffee=1,milk=1,chocolate=0,sugar=1)

Hibernate would then create records in the table like the following:

id (int) name (varchar) price (int) coffee (int) milk (int) chocolate (int) sugar (int)
1 Black Coffee 1 1 0 0 0
2 Mocha 3 1 1 0 1

How do we handle scenarios where we want to create more complicated Recipes, such as a Pumpkin Spice Latte? Our current approach would require us to modify our database schema, which is often difficult to do in-place (that is, without destroying the data that we already have stored). Thus, we’d ideally like to abstract out the ingredients and their amounts associated with a Recipe into an Ingredient class, and then allow a Recipe to have multiple, arbitrary Ingredients that are associated with it.

We’ll start by creating ingredients at every layer of the system.

Ingredient Persistence

In the previous section, we laid out an overview of a design for how we would like to structure the new-and-improved version of CoffeeMaker, and discussed joins we could use to solve the problem. Now, let’s start implementing it, a piece at a time.

For the workshop, you can skip commenting your code. We will expect your code to be fully commented for your full implementation.

Creating the IngredientType enum

The first task is to create a representation of a specific type of Ingredient that can get added to a recipe. Enumerations don’t get saved directly into the database, so create a new package called edu.ncsu.csc326.coffee_maker.entity.enums, then create a new Enum inside this package called IngredientType. (Please call yours the same thing to enable some of the other example code to work.) Once you’ve created the enum, add in several values representing things you’d enjoy in a coffee. Please make sure it at least contains “COFFEE”, “MILK” and “PUMPKIN_SPICE” as we are going to make delicious coffee! And example is below:

public enum IngredientType {
	COFFEE,
	MILK,
	SUGAR,
	CHOCOLATE,
	PUMPKIN_SPICE,
	APPLE_CIDER
}

Create Ingredient

The next step is to create an Ingredient class – something we can actually store in the database that represents a specific ingredient (as given in our enumeration), with a specific quantity as needed by recipes. Start off by creating an Ingredient class under the edu.ncsu.csc326.coffee_maker.entity package (note, not the entity.enums package – alongside the existing Recipe class). Here are some key things to consider when you make a new persistent class:

  • Add the @Entity annotation up above your class definition. This signifies that the class is something that will get persisted to the database.

Ingredient should define three fields:

  • An id field, which serves as the primary key for the database to reference things so that we can keep track of them and reference them from other tables later. Make this a Long.
  • An ingredientType field, which uses our IngredientType enumeration.
  • An amount field. An Integer is probably most reasonable here.

Next, use IntelliJ to generate a constructor that takes an IngredientType and an amount (no id), and getters/setters. All of these are available from Code > Generate… (Alt+Insert on Windows/Linux, Cmd+N on macOS) with your cursor inside the class — pick Constructor or Getter and Setter. You’ll also want to create a constructor that takes no arguments for Hibernate to use when loading objects from the database.

Create IngredientRepository

CoffeeMaker are built using the Spring Boot framework, a popular framework for creating enterprise-class Java applications. Spring will handle most of the hard work of saving our objects to the database (and, naturally, retrieving them later on), but we need to do a bit more work to tell it how to do so.

Under the repositories package, go create a new interface and call it IngredientRepository. The body of this interface will be empty (i.e., there will be no methods inside of it) but make sure to extend from JpaRepository. When you’re done, you should have something like:


package edu.ncsu.csc326.coffee_maker.repositories;

import org.springframework.data.jpa.repository.JpaRepository;

import edu.ncsu.csc326.coffee_maker.entity.Ingredient;

public interface IngredientRepository extends JpaRepository<Ingredient, Long> {

}

You might reasonably be wondering, “What good does it possibly do to create an empty interface like this?”. Well, what this does is tell Spring that we are interested in storing Ingredient objects in the corresponding table, each of which is identified by a Long as the primary key. Note that, in a general sense, the ID doesn’t need to be a Long, but for consistency with the Ingredient we defined above, it needs to be one here. For more information, you can check out the Spring docs which explain a bit more on how this works.

Test IngredientRepository

We’ll take a moment here to test IngredientRepository and ensure that we’re interacting with the database correctly.

Create IngredientRepositoryTest in the src/test/java/ edu.ncsu.csc326.coffee_maker.repositories package.

You can copy the provided test code:

package edu.ncsu.csc326.coffee_maker.repositories;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import edu.ncsu.csc326.coffee_maker.entity.Ingredient;
import edu.ncsu.csc326.coffee_maker.entity.enums.IngredientType;
import jakarta.transaction.Transactional;

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class IngredientRepositoryTest {
	
	@Autowired
	private IngredientRepository ingredientRepository;
	
	private Long ingredient1Id;
	private Long ingredient2Id;

	@BeforeEach
	public void setUp() throws Exception {
		ingredientRepository.deleteAll();
		
		Ingredient ingredient1 = new Ingredient(IngredientType.COFFEE, 5);
		Ingredient ingredient2 = new Ingredient(IngredientType.PUMPKIN_SPICE, 10);
		
		ingredient1Id = ingredientRepository.save(ingredient1).getId();
		ingredient2Id = ingredientRepository.save(ingredient2).getId();
		
		System.out.println(ingredient1Id + " " + ingredient2Id);
	}

	@Test
	@Transactional
	public void testAddIngredients() {
		Ingredient i1 = ingredientRepository.findById(ingredient1Id).get();
		assertAll("Ingredient contents",
				() -> assertEquals(ingredient1Id, i1.getId()),
				() -> assertEquals(IngredientType.COFFEE, i1.getIngredientType()),
				() -> assertEquals(5, i1.getAmount()));
		
		Ingredient i2 = ingredientRepository.findById(ingredient2Id).get();
		assertAll("Ingredient contents",
				() -> assertEquals(ingredient2Id, i2.getId()),
				() -> assertEquals(IngredientType.PUMPKIN_SPICE, i2.getIngredientType()),
				() -> assertEquals(10, i2.getAmount()));
	}

}

This test class has access to the IngredientRepository. Before each test method, we clear the database and create 2 new ingredients and save them. We store the ids as fields since the id values will change with each test run.

The testAddIngredients() method checks that we can retrieve the Ingredients by id and checks that the contents are correct.

Run your tests and ensure that they pass.

Implement IngredientDto

Before we can implement IngredientService we need to create our data transfer object (DTO) for Ingredient. Create a new IngredientDto class in the dto package.

The implementation should match Ingredient without annotations.

Implement IngredientMapper

Now we need to map between Ingredient and IngredientDto. Create IngredientMapper in the mapper package.

Since we have constructors in Ingredient and IngredientDto that do not contain the id, we should construct the object we’re mapping to and set the fields. An implementation is below:

public class IngredientMapper {
	
	public static IngredientDto mapToIngredientDto(Ingredient ingredient) {
		IngredientDto ingredientDto = new IngredientDto();
		ingredientDto.setId(ingredient.getId());
		ingredientDto.setIngredientType(ingredient.getIngredientType());
		ingredientDto.setAmount(ingredient.getAmount());
		return ingredientDto;
	}	
	
	public static Ingredient mapToIngredient(IngredientDto ingredientDto) {
		Ingredient ingredient = new Ingredient();
		ingredient.setId(ingredientDto.getId());
		ingredient.setIngredientType(ingredientDto.getIngredientType());
		ingredient.setAmount(ingredientDto.getAmount());
		return ingredient;
	}

}

Services

Services Background

The services layer provides the business logic of the CoffeeMaker system. It will receive calls from the API endpoints and will do the necessary work to accomplish the main tasks of the system. Updates to persistent data are made through the corresponding repositories. You should have a service class for each entity. You can also have services that work with multiple entities (e.g., MakeRecipeService.

Ingredient Service

Implement IngredientService

Next, we’ll write the second class that lets Spring work its magic. Under the services package, create a new interface IngredientService. IngredientService should define the following behaviors:

public interface IngredientService {
	
	IngredientDto createIngredient(IngredientDto ingredientDto);
	
	IngredientDto getIngredientById(Long ingredientId);
	
	List<IngredientDto> getAllIngredients();
	
	void deleteIngredient(Long ingredientId);
	
	void deleteAllIngredients();

}

Implement IngredientServiceImpl

Create IngredientServiceImpl in the services.impl package. IngredientServiceImpl should implement IngredientService.

Add the @Service annotation to the class header.

Add an @Autowired field for IngredientRepository.

Implement the methods. You can use the provided RecipeServiceImpl and InventoryServiceImpl to provide guidance on what the implemented should look like.

Test IngredientServiceImpl

Now we have a Java class defined, let’s run some minimal tests to see if things are working. Create IngredientService[Impl]Test in the src/test/java/ folder’s services package. (Including *Impl* in the test name is optional. We ask for consistency, so if you want to include it, you should refactor any other tests to match the pattern.)

@SpringBootTest
public class IngredientServiceImplTest {
	
	@Autowired
	private IngredientService ingredientService;

	@BeforeEach
	public void setUp() throws Exception {
		ingredientService.deleteAllIngredients();
	}

	@Test
	@Transactional
	public void testCreateIngredient() {
		
		IngredientDto ingredient1 = new IngredientDto(IngredientType.COFFEE, 5);
				
		IngredientDto createdIngredient1 = ingredientService.createIngredient(ingredient1);
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.COFFEE, createdIngredient1.getIngredientType()),
				() -> assertEquals(5, createdIngredient1.getAmount()));
		
		IngredientDto ingredient2 = new IngredientDto(IngredientType.PUMPKIN_SPICE, 10);
		IngredientDto createdIngredient2 = ingredientService.createIngredient(ingredient2);
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.PUMPKIN_SPICE, createdIngredient2.getIngredientType()),
				() -> assertEquals(10, createdIngredient2.getAmount()));
	}
	
	@Test
	@Transactional
	public void testGetIngredientById() {
		
		IngredientDto ingredient1 = new IngredientDto(IngredientType.COFFEE, 5);
				
		IngredientDto createdIngredient1 = ingredientService.createIngredient(ingredient1);
		IngredientDto fetchedIngredient1 = ingredientService.getIngredientById(createdIngredient1.getId());
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.COFFEE, fetchedIngredient1.getIngredientType()),
				() -> assertEquals(5, fetchedIngredient1.getAmount()));
		
		IngredientDto ingredient2 = new IngredientDto(IngredientType.PUMPKIN_SPICE, 10);
		IngredientDto createdIngredient2 = ingredientService.createIngredient(ingredient2);
		IngredientDto fetchedIngredient2 = ingredientService.getIngredientById(createdIngredient2.getId());
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.PUMPKIN_SPICE, fetchedIngredient2.getIngredientType()),
				() -> assertEquals(10, fetchedIngredient2.getAmount()));
	}

}

This test clears the database before each test. We test creating new ingredients and getting ingredients by id.

Controllers

Now that we’ve seen how to work with databases for long-term storage of information within our system, the next step is figuring out how to get information into and out of the application we’re writing. While we’ve not yet gotten to the step of writing the dynamic parts of our frontend, when we get there, we’ll see it’s impossible to have Javascript code directly call the Java code we’ve written. The JVM runs a tight ship when it comes to security and who is allowed to do what, and Javascript from a front end will be promptly rejected.

So, how does the frontend communicate with the backend? The answer is over a REST API, which lets us write Java code that can be interacted with via HTTP requests to the web application server that runs the backend code. Here, we’ll see how that works and how to write your own REST APIs.

Controller Background

We covered some background on what APIs are during the Testing Workshop and the Backend Design Workshop, but we’ll revisit the material with a focus on implementation and testing.

An API (or Application Programming Interface) defines a specification for how to communicate with a software system. An API lays out what functionality is offered, what parameters must be provided when making calls, and provides some guarantees about the return type given the preconditions of the call are satisfied. Fundamentally, a complete and well-documented API makes it easier to use a piece of code as a “building block” for building a larger system.

A REST API is a subtype of API that is geared towards Internet-facing systems. The goal of REST APIs is to provide painless communication and interoperability between these Internet-facing applications and systems. REST APIs typically allow (often with some sort of authentication) a manipulation of the various types of entities (recipes, inventory, ingredients, etc.) that a web application revolves around.

The key concept behind REST APIs is that they are inherently stateless, that is, everything that a server needs to know to complete a request or a client needs to know about the results is contained within the request itself. This is contrary to the notion of a server maintaining a session where it stores information about a series of transactions with a particular client, or cookies where a client keeps similar information stored on its end.

Typically, REST API operations are carried out over HTTP; consequently most REST API actions are based around HTTP verbs (POST, PUT, DELETE, and so on). The actions typically available are:

HTTP Verb Action Example Result
GET Retrieve record(s) GET /users/ Retrieves all users
DELETE Delete record(s) DELETE /users/1 Deletes user with id 1
POST Create record POST /users/ Creates a new user
PUT Update record PUT /users/6 Updates user 6

There are other HTTP verbs available, but the four above will let us accomplish everything that we need without making things too complicated.

Our prior discussion of REST APIs was limited to treating them as a black box – all that we cared was when you send data to an API endpoint, the API will go do something and then respond accordingly. Today we’re going to figure out how that something is done by seeing how to implement a few different API endpoints.

REST APIs in Spring

Fundamentally, all REST APIs work by sending and receiving JSON. We saw how JSON works before, but at its core, it’s a way of “flattening” objects down into key-value pairs so that you can easily transmit them across a network. From our point of view, this means that on the frontend you build up a JSON structure based on what the API expects, send it by making an API call, and then will get back JSON according to the API’s specification.

From the backend, however, we don’t work directly with JSON. Instead, we work with normal Java objects, and Spring will handle converting these to and from JSON. This is a process known as serialization (going from Java to JSON) or deserialization (going from JSON to Java). The advantage of this is that we get to enjoy all of the benefits of static typing when writing the REST APIs, and the pain points of “but wait, this data doesn’t look like what I expect” is limited to just two points: 1) when the data gets deserialized to Java objects, and 2) when you’re working with the serialized JSON on the frontend.

We’ll see how this works in a few minutes when we look at method parameters and return values from the API endpoint methods that we write.

Ingredient Controller

We’ll be working on some of the API endpoints for your Ingredient object. To get started, we’ll need to create a new Java class to hold these methods. The way that the CoffeeMaker system is designed is that for each class that gets persisted to the database (that is, the ones under entity) there’s a matching class that provides the API endpoints for doing things with that object (under controllers). You can have other controller classes that correspond to services that utilize multiple repositories (e.g., MakeRecipeController).

Create a new class, IngredientController in the controllers package . Add the following annotations:

  • @CrossOrigin("*"): allows for access when a request is coming from a different port
  • @RestController: indicates to Spring, “this is a class where I want to keep REST API endpoints” and that helps it know that parameters to/from these methods should be automatically serialized/deserialized.
  • @RequestMapping("/api/ingredients"): specifies the path for the endpoints associated with this class. We could also use this annotation on methods if there isn’t a common endpoint path for a class.

Once you’ve done that, you should have a class that looks like the following:

@CrossOrigin("*")
@RestController
@RequestMapping("/api/ingredients")
public class IngredientController {

}

Endpoint Templates

Let’s look at a general template for endpoint methods. The code below is a method with an optional list of parameters that will return a ResponseEntity. The method will contain code appropriate for the action and after the action is complete, we’ll create a ResponsEntity that will wrap up the data to return with an HttpStatus that indicates if the result was successful or not.

The method has a leading annotation that indicates the type of HTTP request we’re making, the URL that a caller would use for this request, and any additional information needed for the request.

@MappingType( URL this API endpoint is available at ) //if @RequestMapping is used at the class level, only add extra parts to the URL
public ResponseEntity<AppropriateGenericType> methodName ( PARAMETERS ) {

    /* Go do so something */

    return new ResponseEntity(Data to return, HttpStatus indicating what happened);
}

GET Ingredient Endpoint

Suppose we’re creating an API endpoint to retrieve a single Ingredient. The method might look like:

@GetMapping("{id}")
public ResponseEntity<IngredientDto> getIngredient(@PathVariable("id") Long id) {
	IngredientDto ingredientDto = ingredientService.getIngredientById(id);
	return ResponseEntity.ok(ingredientDto);
}

Let’s discuss each part of the method:

  • @GetMapping indicates that this API endpoint will respond to GET requests.
  • {id} creates a wildcard where the user can pass in the id of the specific ingredient they want. Spring will handle this automatically, provided that….
  • You also have something like @PathVariable("id") Long id defined as a parameter to the method. This says “I expect there to be a variable passed in by the user, and it’s going to be part of the path (URL)”. Matching is done on name, which means you can pass multiple parameters (we’ll see a slightly tortured example of this in a moment).
  • The body of the method calls methods in the persistent class to get the Ingredient. This is the “go do something” portion of the method.
  • return ResponseEntity.ok(ingredientDto); says we’ll return a ResponseEntity, which is one of the special types that Spring will automatically turn into JSON data for us. .ok() is a static method used to indicate that everything worked. More response codes you can use are available from http.cat. Generally you’ll use 2xx codes to indicate everything worked fine, 4xx to indicate the user did something wrong, and 5xx to indicate the server did something wrong.

If there’s an error (e.g., there’s no ingredient with that id), the service will throw the exception that will be passed out through the controller with the appropriate response code.

You can then call this API endpoint with a call similar to GET /api/ingredients/1, which would either return the details of the ingredient if it exists or a 404 NOT FOUND if it doesn’t.

As mentioned above, you can pass multiple parameters to the API endpoint. This means if we wanted to create some sort of “universal” API endpoint for retrieving any object, we could do something like:

@GetMapping("{object}/{field}/{value}")
public ResponseEntity getObject ( @PathVariable final String object, @PathVariable final String field,
        @PathVariable final String value ) {
    try {
        switch(object){
		    case "Ingredient": // go do something
			break;
			
			case "Recipe": // go do something else
			break;
		}

        if ( null == obj ) {
            return new ResponseEntity( HttpStatus.NOT_FOUND );
        }

        return new ResponseEntity( obj, HttpStatus.OK );

    }
    catch ( final Exception e ) {
        return new ResponseEntity( "Something went wrong with your request :: " + e.getCause(),
                HttpStatus.BAD_REQUEST );
    }

}

If I call it with values that exist in my database, for instance GET api/recipes/name/SweetLoot I get a valid response back: 200: {"id":1,"name":"SweetLoot","price":50,"coffee":1,"milk":2,"sugar":3,"chocolate":4}. If instead I call it with nonsense (GET api/v1/nope/nothere/orhere), I likewise get back nonsense: 400: Something went wrong with your request :: null.

This is not strictly a good idea, but it shows how we can have multiple parameters as part of the URL, and Spring will auto-magically map from each one in the URL to one within the Java method parameter list.

POST Ingredient Endpoint

Let’s create a POST endpoint for the IngredientController:

@PostMapping
public ResponseEntity<IngredientDto> createIngredient(@RequestBody IngredientDto ingredientDto) {
	IngredientDto savedIngredientDto = ingredientService.createIngredient(ingredientDto);
	return ResponseEntity.ok(savedIngredientDto);
}

Let’s unpack what we’re doing here, a piece at a time:

  • @PostMapping: This says we’re going to respond to a POST request at the given URL.
  • @RequestBody IngredientDto ingredientDto: This says that we expect to get an IngredientDto that is sent as JSON data alongside the request. For now, we won’t focus on how the frontend does this, but the important part is that you can send one “blob” of JSON alongside the request.

REST APIs: Special Cases, Caveats and Pitfalls

This really is basically all there is to writing (simple) REST APIs in Spring. However, there are a few more things to be aware of before you start writing many of your own:

  • When want to retrieve a bunch of objects, you don’t return a ResponseEntity, but instead use a List. A list with all matching elements we found indicates we got something, and a list with no objects means there was nothing. Spring will auto-magically serialize this to JSON too:
@GetMapping
    public List<RecipeDto> getRecipes () {
        return recipeService.getAllRecipes();
    }
  • GET (and DELETE) routes don’t support extra JSON data sent alongside the request (the extra data is what would be turned into a RequestBody as in the POST example). Only POST and PUT let you do this. Thus, if you want to make a complicated retrieval request (for instance, “Give me all users whose name starts with Ja born between 1950 and 1965”) it would create a really nasty GET request because of all of the parameters that would go in the URL. You thus would be better off with a POST request, where the details of what you want become a blob of JSON sent with the request. This is reasonably common for performing requests where the server will need to do more extensive lookup.
  • Spring makes a best-effort approach to convert from your JSON data into Java objects of the appropriate type. However, if you do something wrong, the conversion will fail and your request won’t go through. For instance, if we have an API endpoint such as:
@GetMapping("/recipes/id/{id}")
public ResponseEntity getRecipeById(@PathVariable("id") Long id ) {
    return new ResponseEntity( recipeService.findById( id ), HttpStatus.OK );
}

and then call it as:

GET /api/v1/recipes/id/notreallyanumber Spring will give us an error back:

> Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "notreallyanumber"

This is pretty easy to quickly solve (or better yet, never cause in the first place) when making simple GET requests such as this. However, if you’re making a POST or PUT request with a more complicated object, and it can’t be properly deserialized, it can be a bit more difficult to track down what’s gone wrong. In this case, you’ll likely want to use Postman or the Debugger in your browser, and inspect the request that was sent to the server to see exactly the structure of the data sent.

  • If you forget the appropriate annotations on your method parameters (@RequestBody/@PathVariable) then Spring won’t know to match data received from the API endpoint to your method parameters, and you’ll get null. If you’re not getting anything and think you should be, take a look at it.

Test IngredientController

Test IngredientController with the following:

@SpringBootTest
@AutoConfigureMockMvc
public class IngredientControllerTest {
	
	/** Mock MVC for testing controller */
	@Autowired
	private MockMvc mvc;

	@Test
	@Transactional
	void testCreateIngredient() throws Exception {
		IngredientDto ingredient1 = new IngredientDto(IngredientType.COFFEE, 5);
		
		mvc.perform(post("/api/ingredients")
			.contentType(MediaType.APPLICATION_JSON)
			.content(TestUtils.asJsonString(ingredient1))
			.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk())
			.andExpect(jsonPath("$.amount").value("5"))
			.andExpect(jsonPath("$.ingredientType").value("COFFEE"));
	}

}

This test is calling the POST ingredient end point and checking the JSON contents is correct afterwards. Note that we’re not checking for an id b/c the value will change every time we run the tests.

System Testing

Let’s run some system tests through Postman! Start your application.

Test ID: Create Coffee Ingredient

  • Test Description:
    • HTTP Request: POST
    • URL: http://localhost:8080/api/ingredients
    • Body:
{
	"ingredientType":"COFFEE",
	"amount":5
}
  • Expected Result
    • Response Code: 200
    • Response Body:
{
	"id": #, //some value 1 or more - this will vary
	"ingredientType":"COFFEE",
	"amount":5
}

After you run the test, check the coffee_maker schema in the database. Run the query select * from ingredients;. The results should look something like the following:

id amount ingredient_type
1 5 0

There’s one small thing that we’d like to fix before we move on, however: the values being stored under the ingredient_type column. What are these numbers? This doesn’t make sense! We didn’t define our ingredient field as ints, so why do we get this here? The short answer is that Java’s enums all have both a String value – the friendly name that you give them – and an integer value – that represents their ordinal position out of the values you’ve defined. By default, Hibernate saves the integer value to the database. It’s helpful to see the string value when working with the database so you can then look at the data that’s stored in the database and it actually means something. To fix this, add the following annotation above the ingredient field:

@Enumerated ( EnumType.STRING )

This tells Hibernate to save the String value of the enumeration to the database instead of just an int value. Stop your application from running and drop the existing schema. Rerun your application and run your system test again. Now you should see the following:

id amount ingredient_type
1 5 COFFEE

Test ID: Create Apple Cider Ingredient

  • Test Description:
    • HTTP Request: POST
    • URL: http://localhost:8080/api/ingredients
    • Body:
{
	"ingredientType":"APPLE_CIDER",
	"amount":3
}
  • Expected Result
    • Response Code: 200
    • Response Body:
{
	"id": #, //some value 1 or more - this will vary
	"ingredientType":"APPLE_CIDER",
	"amount":3
}

Test ID: Unknown Ingredient

  • Test Description:
    • HTTP Request: POST
    • URL: http://localhost:8080/api/ingredients
    • Body:
{
	"ingredientType":"CHAI",
	"amount":2
}
  • Expected Result
    • Response Code: 400
    • Response Body:
{
	"timestamp": "2024-09-19T01:44:45.063+00:00", // your timestamp will vary
    "status": 400,
    "error": "Bad Request",
    "path": "/api/ingredients"
}

Commit/Push

At this point, Ingredient* should be implemented and (minimally) tested.

Don’t forget to tie the commit to the issue as part of the commit message!

Onward

We’ve created the idea of ingredients in our CoffeeMaker system and implemented the functionality through all layers of the system. Now we can set up the composition relationship between Recipe and Ingredient. Proceed to Part 2: Recipe Implementation.