Here is an example code demonstrating the issue:
The Meal Entity:
@Entity
public class Meal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(mappedBy = "meal", cascade = CascadeType.PERSIST)
private Collection<Food> foods;
public Meal() {
foods = new HashSet<>();
}
public Collection<Food> getFoods() {
return foods;
}
public void addFood(Food food) {
foods.add(food);
// without this the `meal_id` column is null
food.setMeal(this);
}
}
The Food Entity:
@Entity
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
private Meal meal;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Meal getMeal() {
return meal;
}
public void setMeal(Meal meal) {
this.meal = meal;
}
}
And here is the code that creates and saves the entities:
Meal meal = new Meal();
for (int i = 0; i < 10; i++) {
meal.addFood(new Food());
}
mealRepository.save(meal);
Both the Meal and the Food entities are persisted thanks to the CascadeType.PERSIST
, but the meal_id
column stays null if I don't explicitly set the meal
field to the Meal entity.
This is not the behavior I'd expect, and I'm wondering why isn't this automatically done for me.