简体   繁体   English

SpringBoot - 关系的实体传播

[英]SpringBoot - Entity propagation for relationships

I have two entities: WorkoutTemplate and ConcreteExercise.我有两个实体:WorkoutTemplate 和 ConcreteExercise。

In WorkoutTemplate I have this relationship with ConcreteExercises在 WorkoutTemplate 我与 ConcreteExercises 有这种关系

@OneToMany(cascade = CascadeType.ALL, mappedBy = "belongingWorkout", fetch = FetchType.LAZY)
private List<ConcreteExercise> concreteExercises;

And in ConcreteExercise I have this relationship with WorkoutTemplate在 ConcreteExercise 我与 WorkoutTemplate 有这种关系

@ManyToOne
private WorkoutTemplate belongingWorkout;

I would like to insert a WorkoutTemplate into my database... I make the request to the controller sending a Json like this:我想在我的数据库中插入一个 WorkoutTemplate ......我向 controller 发出请求,发送一个 Json,如下所示:

{ "workoutName" : "My Workout",
concreteExercises: [
   {
"name" : "Squat"
   } 
 ]
}

The DAO insert into my DB the WorkoutTemplate And insert also in the table of the ConcreteExercise the name. DAO 将 WorkoutTemplate 插入到我的数据库中,并将名称也插入到 ConcreteExercise 的表中。 But not the reference to the WorkoutTemplate... Practically, the table ConcreteExercise is made of:但不是对 WorkoutTemplate 的引用......实际上,表格 ConcreteExercise 由以下各项组成:

id, name, belongin_workout_id

With the request above, we populate the id (auto-increment) and the name, but not the foreign key to the WorkoutTemplate.使用上面的请求,我们填充了 ID(自动增量)和名称,而不是 WorkoutTemplate 的外键。

How can I solve this?我该如何解决这个问题? I would like to automatically insert the foreign key without sending it in the request or doing it manually into the service我想自动插入外键而不在请求中发送或手动将其插入服务

Hi there it's because you are not using @JoinColumn which marks a column for as a join column for an entity association or an element collection.您好,这是因为您没有使用@JoinColumn将列标记为实体关联或元素集合的连接列。

On your WorkoutTemplate entity - you can retain this:在您的WorkoutTemplate实体上 - 您可以保留以下内容:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "belongingWorkout", fetch = FetchType.LAZY)
private List<ConcreteExercise> concreteExercises;

But on your ConcreteExercise entity - you need to have this change:但是在您的ConcreteExercise实体上-您需要进行此更改:

@ManyToOne
@JoinColumn(name = "workout_template_id", nullable = false)
private WorkoutTemplate belongingWorkout;

The above code will create a foreign key linking the ConcreteExercise entity with the primary key from the WorkoutTemplate entity.上面的代码将创建一个外键,将ConcreteExercise实体与WorkoutTemplate实体的主键链接起来。 The name of the foreign key column in the ConcreteExercise entity is specified by name property which for this case is workout_template_id - feel free to change this. ConcreteExercise实体中的外键列的名称由name属性指定,在本例中为锻炼模板 ID - 随意更改。

If you have set this up but still not working, it will also be helpful to share a code snippet on how are you saving these.如果您已经设置了它但仍然无法正常工作,那么分享一个关于如何保存这些的代码片段也会很有帮助。

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

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