Skip to main content

Updated for Fall 2026

Entity Composition

So, what we’ve seen so far is that it’s possible to create Java objects that get automatically converted into rows in a database table when we call the save() method. But, so far, all that we have created is a very simple class – a single Java class whose fields are all primitives or other built-in types (e.g., a String). This is not particularly representative of how most real-world entities actually look. So, next, we’ll learn how to compose together objects out of more complicated types and have them persist in the database.

In object-oriented languages like Java, one of the fundamental relationships between classes is composition – one object has a field that is an instance of another object. Java maintains a reference to the object in memory. Dereferencing (i.e., the “.” notation) the field let’s you work with the field’s (public) state and behaviors. But, how does this work for database entities? The answer is primary keys and foreign keys.

Primary Keys

Most database entities that you will work with will have a primary key. A primary key is a column (or set of columns) within a table that is guaranteed to be unique. In the Recipes table above, the id column is the primary key for the entity; there can never be two recipes that have the same id. This is similar to Unity IDs – each ID is guaranteed to be unique to one and only one person. This is useful because although there might be multiple types of Mocha recipe, we now have a guaranteed way to refer to our Mocha recipe from above.

Foreign Keys

Foreign keys work very similarly to primary keys – they are a way to uniquely identify a single row within a table. However, instead of uniquely identifying a record within the current table, a foreign key uniquely identifies a record within a different table. How does it do this? A foreign key in Table A will contain the same value that is stored in the primary key for a row in Table B – thus giving us a direct reference to another object. Thus, this basically gives us a way to uniquely reference an object that exists in another table that we care about. We’ll see in a moment how to define these in Hibernate, and what it then looks like when actual database tables get created from it.

Joining Entities in Hibernate

How does all of this actually work in Hibernate? Hibernate is a very powerful framework, that gives you the ability to represent nearly anything that a relational database is capable of. One powerful way to work with multiple tables is through the idea of a join, which brings information in tables together. Our composition relationship is supported through joins of tables in a database.

We’ll focus on the following annotations that support joining entities in a database and tying them to the objects in our application:

  • @OneToOne
  • @OneToMany

OneToOne is exactly like the one-to-one composition relationship you learned in CSC 216 – it establishes that for each entity of Object A, there is one associated entity of Object B.

OneToMany lets us map between the recipe we’ve created and the ingredients that go into it. This is a relationship that handles multiplicity; each individual recipe can have zero, one, or many ingredients. @OneToMany lets have a collection of an object as the field of one of our persistent classes.

Design Overview

Our goal is to decouple the recipe from the ingredients that are associated with it instead of a recipe that can only have 4 ingredients. In our current Recipe implementation, we always have 4 ingredients and we are storing 0s for any of the ingredients that aren’t part of the recipe. That is wasted space. Instead, we want to create recipes that can have only the ingredients appropriate for the recipe.

To explore the functionality of Hibernate, we’re going to explore a partial solution of the arbitrary ingredients requirements. The work that you’ll do in this workshop is a start towards meeting the new requirements, but it is not sufficient because the enumerated types do not support dynamic ingredient types when adding or editing recipes.

For this workshop, we’ll create an IngredientType enumeration, which represents a specific type of ingredient that you’d put into a recipe (such as Coffee, Milk, Sugar, or Pumpkin Spice). Then, we want an Ingredient class that represents a specific amount of one of the previous ingredients (such as, {Coffee, 10} or {Pumpkin Spice, 5}) that are used to make the recipe.

Then we want our Recipe class to keep track of an arbitrary number of these Ingredient instances, so that we can build up any type of recipe without changing our database schema.

In short, we want a collection (in Java nomenclature, a List, or Set, or similar) of some sort of element (Ingredients) that gets attached to our Recipe. This is what the OneToMany join lets us do – we can specify, in the Recipe class, that we have a collection of some other type (in our case, Ingredient) that Hibernate then handles saving it to the database.

Persistence

Recipe Persistence

So far we’ve created an enumeration that contains various ingredient types, and created an Ingredient class that represents a certain amount of an ingredient. But, what we don’t have – yet – is the Recipe using these new Ingredients.

Update Recipe

Complete the following tasks:

  • Create a field of type List<Ingredient> and call it ingredients or similar.
  • Modify both Recipe constructors to initialize this list to an empty list (either ArrayList or LinkedList are OK). If we don’t create an empty list, we’ll get NPEs!
  • Define the addIngredient() method that will take in a single Ingredient to add to this list
  • Define the getIngredients() method that returns the entire list

Test RecipeRepository

Now that we’ve added a list of Ingredients to Recipe, let’s update our RecipeRepositoryTest to test this new functionality. You can copy in the provided code to supplement your current tests.

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class RecipeRepositoryTest {
	
	/** Reference to recipe repository */
	@Autowired
	private RecipeRepository recipeRepository;
	
	@Test
	public void testAddIngredients() {
		Recipe recipe1 = new Recipe("Coffee", 500);
		recipe1.addIngredient(new Ingredient(IngredientType.COFFEE, 3));
		recipe1.addIngredient(new Ingredient(IngredientType.PUMPKIN_SPICE, 2));
		recipe1.addIngredient(new Ingredient(IngredientType.MILK, 1));
		
		Recipe savedRecipe = recipeRepository.save(recipe1);
		Optional<Recipe> retrievedRecipe = recipeRepository.findById(savedRecipe.getId());
		assertAll("Recipe contents",
				() -> assertEquals("Coffee", retrievedRecipe.get().getName()),
				() -> assertEquals(500, retrievedRecipe.get().getPrice()),
				() -> assertEquals(3, retrievedRecipe.get().getIngredients().size()));
		
		Ingredient i1 = retrievedRecipe.get().getIngredients().get(0);
		Ingredient i2 = retrievedRecipe.get().getIngredients().get(1);
		Ingredient i3 = retrievedRecipe.get().getIngredients().get(2);
		
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.COFFEE, i1.getIngredientType()),
				() -> assertEquals(3, i1.getAmount()));
		
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.PUMPKIN_SPICE, i2.getIngredientType()),
				() -> assertEquals(2, i2.getAmount()));
		
		assertAll("Ingredient contents",
				() -> assertEquals(IngredientType.MILK, i3.getIngredientType()),
				() -> assertEquals(1, i3.getAmount()));
	}

}

The testAdIngredients() method creates a new recipe and adds three ingredients. We then retrieve the recipe and check that the contents are correct.

Run RecipeRepositoryTest.

After running this class you should see the following error:

~snip~
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Basic collection has element type 'edu.ncsu.csc326.coffee_maker.entity.Ingredient' which is not a known basic type (attribute is not annotated '@ElementCollection', '@OneToMany', or '@ManyToMany')

We seem to have run into an issue. What happened? Hibernate can’t figure out how to turn our List<Ingredient> into a column that it can store in the database. Why is this? Well, a fundamental of database design is that a given column can generally store only a single value – not an entire collection of values. So, this brings is back to the joins that we talked about earlier – we need to tell Hibernate to keep a reference to each of the Ingredients, and to do so by using an extra table. So, let’s do that.

Add the annotation @OneToMany above the ingredients field in Recipe. You should now have something like this:

@OneToMany
private List<Ingredient> ingredients;

Run RecipeRepositoryTest again.

Saving, saving, and more saving

When you ran the RecipeRepositoryTest test in the previous step, the testAddIngredients() test fails. We expect that the first Ingredient is COFFEE with an amount of 3. Instead the ingredientType and amount are null.

We’ve just told Hibernate how to persist the ingredients list to the database (and we even did it properly, no tricks here!), so what happened? Well, this brings us back to the discussion of Primary Keys and Foreign Keys from before. A foreign key, essentially, is a reference to the primary key of a record stored in a different table. The advantage of using these keys, instead of storing everything in a String, is that the database will let us know when we’ve done something wrong – like trying to reference an entity that doesn’t exist yet (not only will it let us know, it will fail our transaction – so it’s impossible to store junk in the database by accident). And, that is exactly what we’ve stumbled upon here. What we’ve done, essentially, is we’ve tried to have the Recipe reference an Ingredient that the database doesn’t know about yet. Thus, there is no way for this foreign key to work properly – you simply can’t have a reference to something that doesn’t exist yet.

So, what is it we’d like to accomplish? Ideally, whenever we save a Recipe object, it should also save all of the Ingredients that are associated with it. Automatically, with no extra user effort required.

How is it that we actually do this? It’s actually surprisingly simple. Go back to the Recipe class, and change @OneToMany to @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER).

What are we doing here? Well, there’s two different parts, so let’s look at each in turn:

  • cascade = CascadeType.ALL: This states that any actions that are performed (i.e., saves, deletes, etc) on our Recipe object should be automatically performed (cascaded) onto the referenced Ingredient objects. This way, saving the Recipe saves all of its ingredients, exactly like we want.
  • fetch = FetchType.EAGER: This states that when we load in the Recipe object from the database, all Ingredients associated with it should be loaded in too. The alternative, lazy loading, can give better performance in some circumstances, and is what Hibernate attempts to do automatically for us. However, how to do it properly is beyond the scope of today’s activity.

After you’ve written your new save method, go run the RecipeRepositoryTest class again. Your tests should pass!

Tada! We’ve now properly linked Recipe to Ingredient, and have it automatically save all ingredients for a recipe to the database whenever the actual Recipe itself gets saved. If you’re still getting an error message, flag down a teaching assistant and let them know.

Update RecipeDto

Update RecipeDto to match Recipe.

  • Create a field of type List<Ingredient> and call it ingredients or similar.
  • Modify both RecipeDto constructors to initialize this list to an empty list (either ArrayList or LinkedList are OK). If we don’t create an empty list, we’ll get NPEs!
  • Define the addIngredient() method that will take in a single Ingredient to add to this list
  • Define the getIngredients() method that returns the entire list

Update RecipeMapper

Update RecipeMapper. Now that we have a collection, we’ll need to create an object to map to and then call the appropriate setters. We’ll loop to add the Ingredients. See the implementation below:

public class RecipeMapper {
	
	/**
	 * Converts a Recipe entity to RecipeDto
	 * @param recipe Recipe to convert
	 * @return RecipeDto object
	 */
	public static RecipeDto mapToRecipeDto(Recipe recipe) {
		RecipeDto r = new RecipeDto (
				recipe.getId(),
				recipe.getName(),
				recipe.getPrice()
		);
		for (int i = 0; i < recipe.getIngredients().size(); i++) {
			r.addIngredient(recipe.getIngredients().get(i));
		}
		return r;
	}

	/**
	 * Converts a RecipeDto object to a Recipe entity.
	 * @param recipeDto RecipeDto to convert
	 * @return Recipe entity
	 */
	public static Recipe mapToRecipe(RecipeDto recipeDto) {
		Recipe r = new Recipe (
				recipeDto.getId(),
				recipeDto.getName(),
				recipeDto.getPrice()
		);
		for (int i = 0; i < recipeDto.getIngredients().size(); i++) {
			r.addIngredient(recipeDto.getIngredients().get(i));
		}
		return r;
	}
	
}

Service

We’ll leave the service layer of the recipe functionality as is. The current behavior is sufficient to demonstrate the composition relationship with system tests.

Additional methods would likely be needed to implement the functionality of adding an Ingredient to a Recipe.

Controller

We’ll leave the controller layer of the recipe functionality as is. The current behavior is sufficient to The current behavior is sufficient to demonstrate the composition relationship with system tests.

Additional methods would likely be needed to implement the functionality of adding an Ingredient to a Recipe.

System Testing

Let’s run some system tests through Postman! You can drop your schema to start with ids of 1.

Don’t forget to start your application!

Test ID: Create Mocha Recipe

  • Test Description:
    • HTTP Request: POST
    • URL: http://localhost:8080/api/recipes
    • Body:
{
    "name": "Mocha",
    "price": 100,
    "ingredients": [
        {
            "ingredientType": "COFFEE",
            "amount": 5
        }, 
        {
            "ingredientType": "MILK",
            "amount": 2
        }, 
        {
            "ingredientType": "CHOCOLATE",
            "amount": 3
        }
    ]
}
  • Expected Result
    • Response Code: 200
    • Response Body:
{
    "id": 1,
    "name": "Mocha",
    "price": 100,
    "ingredients": [
        {
            "id": 1,
            "ingredientType": "COFFEE",
            "amount": 5
        },
        {
            "id": 2,
            "ingredientType": "MILK",
            "amount": 2
        },
        {
            "id": 3,
            "ingredientType": "CHOCOLATE",
            "amount": 3
        }
    ]
}

Note that the JSON wraps the list of ingredients in []s. The ingredients are wrapped in {}s and comma separated in the list.

Test ID: Create Apple Cider Recipe

  • Test Description:
    • HTTP Request: POST
    • URL: http://localhost:8080/api/recipes
    • Body:
{
    "name": "Apple Cider",
    "price": 300,
    "ingredients": [
        {
            "ingredientType": "APPLE_CIDER",
            "amount": 3
        }, 
        {
            "ingredientType": "SUGAR",
            "amount": 2
        }
    ]
}
  • Expected Result
    • Response Code: 200
    • Response Body:
{
    "id": 2,
    "name": "Apple Cider",
    "price": 300,
    "ingredients": [
        {
            "id": 4,
            "ingredientType": "APPLE_CIDER",
            "amount": 3
        },
        {
            "id": 5,
            "ingredientType": "SUGAR",
            "amount": 2
        }
    ]
}

Join Tables

We’ve gotten everything working, but let’s take a look at how the data gets saved before we wrap up here. Go back to MySQL Workbench, refresh the Schema view, expand coffee_maker, and then expand the Tables view. You probably see four tables here:

  • ingredients
  • inventory
  • recipes
  • recipes_ingredients

Wait, what? recipes_ingredients? What’s that doing here? Didn’t we just define two persistence classes, Recipe, and Ingredient? Well, yes. But, as for why we have this – recall above how, before we added any annotations to the List<Ingredient> that we defined, Hibernate was unable to figure out how to save it, because it couldn’t figure out the type? As we saw then, databases won’t save multiple distinct values into a single column. What we did here, and what it resulted in, was a Join Table. As the name implies, a join table is used to join together entities that are stored in two (or more) other tables that exist in the database. Let’s take a look at the table:

recipe_id ingredients_id
1 1
1 2
1 3
2 4
2 5

Basically, this table is used to keep track of which Ingredients are associated with each Recipe, since the Recipe class is itself unable to track the multiple ingredients that make it up. Since we’ve created one Recipe, with three associated Ingredients, we would expect (and do!) see three entries here. They track:

  • Recipe 1 (Mocha) has Ingredient 1 (COFFEE)
  • Recipe 1 (Mocha) has Ingredient 2 (MILK)
  • Recipe 1 (Mocha) has Ingredient 3 (CHOCOLATE)

and

  • Recipe 2 (Apple Cider) has Ingredient 1 (APPLE_CIDER)
  • Recipe 2 (Mocha) has Ingredient 2 (SUGAR)

We can, in fact, get the database to tell us all of this if we tell it to join the multiple queries together. Back in MySQL Workbench, enter in the following query, and then click the lightning bolt icon to execute it:

SELECT * FROM coffee_maker.recipes_ingredients ri, coffee_maker.recipes r, coffee_maker.ingredients i WHERE ri.recipe_id = r.id AND ri.ingredients_id = i.id;

Execute it, and you should see something like this:

recipe_id ingredients_id id name price id amount ingredient_type
1 1 1 Mocha 100 1 5 COFFEE
1 2 1 Mocha 100 2 2 MILK
1 3 1 Mocha 100 3 3 CHOCOLATE
2 4 2 Apple Cider 300 4 3 APPLE_CIDER
2 5 2 Apple Cider 300 5 2 SUGAR

What have we done? We told the database to use this join table here as a “glue” to combine together the other two tables, so that we can see the full names of our recipe, its associated ingredients, and the quantities of each. Normally, you’d tell the database to return just the columns you want, but we’re including all of the IDs here explicitly to see how they glue everything together.

Commit/Push

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

When you’re done with the workshop, check off all the todos in the appropriate issue and close the issue.

Do NOT merge the workshop branch back to main.

You are welcome to use code from this workshop in your full implementation if appropriate for your design.

Onward

You’ve now set up a composition relationship in the backend. You have the tools to get started with your full implementation of arbitrary ingredients. Since this workshop is a partial implementation, you will likely need to reference documentation or other online resources to fully implement the system. Please cite your sources, including any AI tools.

Do NOT merge the workshop branch back to main. You are welcome to use code from this workshop in your full implementation if appropriate for your design.

Return to the main page for the team and individual tasks.