AM13
AM13

Reputation: 683

@One-to-Many relationship does not working in Spring

I have an Entity Recipe with a relationship OneToMany with Ingredients.

@Entity
public class Recipe {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String name;
    @OneToOne(cascade = CascadeType.ALL) // se eliminiamo la Recipe eliminiamo anche notes
    private Notes notes;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
    private Set<Ingredient> ingredients;
    @ManyToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name = "recipe_category",
        joinColumns = @JoinColumn(name = "recipe_id"),
        inverseJoinColumns = @JoinColumn(name = "category_id"))
    private Set<Category> categories;
    ...getter and setter...
}

And an Entity Ingredient:

@Entity
public class Ingredient {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    private int amount;
    @ManyToOne
    private Recipe recipe;
    ...getter and setter...
}

In order to test it I have used a controller to insert and retrieving all row:

    @GetMapping({"","/"})
    public List<Recipe> allRecipe() {
        return recipeRepository.findAll();
    }

    @GetMapping("/insert")
    public Recipe addRecipe() {
        Set<Ingredient> ingredients = new HashSet<>();
        ingredients.add(new Ingredient("ingredient-"+Math.random(), 10));
        Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
                null, ingredients, null);
        return recipeRepository.save(newRecipe);
    }

The repository is a JPA Repository.

I do not have any errors, but when I try to retrieve an object I get no ingredients even though they are saved on the table (but with recipe_id = null). How can I solve this problem?

Upvotes: 0

Views: 78

Answers (1)

Zishan Khan
Zishan Khan

Reputation: 187

Initialize your ingredients as

@OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Ingredient> ingredients = new HashSet<>(); 

Change your your controller to,

@GetMapping("/insert")
    public Recipe addRecipe() {
        Ingredient ingredient = new Ingredient("ingredient-"+Math.random(), 10));
        Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
                null, null); //constructor without ingredient arg
        newRecipe.getIngredients.add(ingredient);
        ingredient.setRecipe(newRecipe);
        return recipeRepository.save(newRecipe);
    }

Upvotes: 2

Related Questions