[英]Remove Object in Map from Many-to-Many Relation
I have an entity Mealplan
, where each weekday (enum)
contains a meal
.我有一个实体
Mealplan
,其中每个weekday (enum)
都包含一meal
。 This is realised with a map and a Many-to-Many relation like this:这是通过 map 和这样的多对多关系实现的:
@Entity
public class Mealplan {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToMany
@SortNatural
private Map<Weekday, Meal> mealsPerWeek;
(...)
}
This means, in my database the mealsPerWeek property is stored in an extra table.这意味着,在我的数据库中,mealsPerWeek 属性存储在一个额外的表中。 "mealplan_meals_per_week".
“mealplan_meals_per_week”。 This table contains the mealplan_id, the meal_per_week_id (mealID) and the weekday_id.
该表包含mealplan_id、meal_per_week_id (mealID) 和weekday_id。
Now, if I remove a Mealplan
, everything gets deleted as I am expecting it.现在,如果我删除
Mealplan
,所有内容都会按照我的预期被删除。 But if I want to delete a Meal
, following SQL error occurs:但是,如果我想删除
Meal
,则会出现以下 SQL 错误:
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referentielle Integrität verletzt: "FKPIBLWWQG1HR2D5W7BGORA9XBB: PUBLIC.ESSENSPLAN_ESSEN_PRO_WOCHE FOREIGN KEY(ESSEN_PRO_WOCHE_ID) REFERENCES PUBLIC.ESSEN(ID) (1)"
Referential integrity constraint violation: "FKPIBLWWQG1HR2D5W7BGORA9XBB: PUBLIC.ESSENSPLAN_ESSEN_PRO_WOCHE FOREIGN KEY(ESSEN_PRO_WOCHE_ID) REFERENCES PUBLIC.ESSEN(ID) (1)"; SQL statement:
delete from essen where id=? [23503-200]
I am expecting that If I delete a Meal, the line in mealplan gets deleted but everything else stays the same.我期待如果我删除一顿饭,膳食计划中的行会被删除,但其他一切都保持不变。
Note: CasdadeType.REMOVE is not an option, because it deletes every Mealplan too, where the meal i want to remove is in it.注意:CasdadeType.REMOVE 不是一个选项,因为它也会删除每个 Mealplan,我要删除的餐点在其中。
@Entity
public class Essen {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
In mealplan_meals_per_week
table there is a reference of Meal
in meal_per_week_id
column.在
mealplan_meals_per_week
表中, meal_per_week_id
列中有Meal
的引用。 So where you are trying to delete Meal
without cascade reference can't be resolved.因此,无法解决您尝试在没有级联引用的情况下删除
Meal
的位置。
So first delete the references of Meal
in mealplan_meals_per_week
table and then delete Meal
.因此,首先删除
mealplan_meals_per_week
表中Meal
的引用,然后删除Meal
。
Since you are not using Entity for mealplan_meals_per_week
, you can use native SQL to define query using nativeQuery.由于您没有将实体用于
mealplan_meals_per_week
,因此您可以使用native SQL 来定义使用nativeQuery 的查询。
@Query(
value = "DELETE FROM mealplan_meals_per_week m WHERE m.meal_per_week_id= ?1",
nativeQuery = true)
void deleteByMealId(Interger mealId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.