简体   繁体   English

@ManyToMany 关系,JPA

[英]@ManyToMany relationship, JPA

I have an issue here, I am trying to make FoodProgram with two entities: FoodProgram-holds 4 meals with List for each meal.我在这里有一个问题,我正在尝试使用两个实体制作 FoodProgram:FoodProgram - 每顿饭都有 4 顿饭和 List。 And FoodEntity with name, calories and id.以及带有名称、卡路里和 ID 的 FoodEntity。 The idea is that each meal can choose from all foods, and foods can repeat in every meal(if we eat eggs for lunch, we can add them to dinner too).这个想法是每顿饭都可以从所有食物中选择,并且每顿饭都可以重复食物(如果我们午餐吃鸡蛋,我们也可以将它们添加到晚餐中)。 I have @ManyToMany annotation in my FoodProgram class.我的 FoodProgram 课程中有 @ManyToMany 注释。 Problem is there, when I try to getLunch from FoodProgram, I got error for lazily initialize, but I cannot put fetchtype.EAGER on every annotation, because I get another error.问题是,当我尝试从 FoodProgram 获取午餐时,我遇到了延迟初始化的错误,但我无法将 fetchtype.EAGER 放在每个注释上,因为我遇到了另一个错误。 Should I just make another entity and to figure out different approach?我应该创建另一个实体并找出不同的方法吗?

FoodEntity食品实体

@Entity
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer calories;

public Food() {
}

FoodProgram entity食品计划实体

@Entity
public class FoodProgram {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
private List<Food> breakfast;
@ManyToMany
private List<Food> lunch;
@ManyToMany
private List<Food> afterLunch;
@ManyToMany
private List<Food> dinner;

public FoodProgram() {
}

With a pure sql model point of view, what's the difference between breakfast, lunch, afterLunch and dinner ?纯sql模型来看,早餐、午餐、后午餐和晚餐有什么区别?

You have two solutions :您有两种解决方案:

  1. you need to implement sql inheritance through your hibernate model first.您需要首先通过您的休眠模型实现 sql 继承。 Have a look at here https://www.baeldung.com/hibernate-inheritance .看看这里https://www.baeldung.com/hibernate-inheritance

  2. you have to specify the dedicated @JoinTable for each relationship您必须为每个关系指定专用的@JoinTable

In other words, your implementation definitely cannot work like this.换句话说,您的实现绝对不能像这样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM