Ser*_*gii 5 java hibernate cascade foreign-key-relationship hibernate-mapping
情况似乎很简单(但它不起作用)。Db 部分(EVENT_ID是外键。表FK_RR_E_CI上的约束引用EVENT)
|-------| |----------------|
| EVENT | 1 ------ ? | RECURRENT_RULE |
|-------| |----------------|
| ID | | ID |
|-------| | EVENT_ID |
|----------------|
Run Code Online (Sandbox Code Playgroud)
Java部分:
@Entity
public class Event {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
private Set<RecurrentRule> recurrentRules = new HashSet<>();
}
@Entity
public class RecurrentRule {
@ManyToOne
@JoinColumn(columnDefinition = "event_id")
private Event event;
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试删除事件对象,它将返回:
could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MY_SCHEMA.FK_RR_E_CI) violated - child record found
Run Code Online (Sandbox Code Playgroud)
SAVE并且UPDATE操作正常。
我应该在映射中更改什么才能使用级联删除?我知道我应该使用@OnDelete(action=OnDeleteAction.CASCADE)但我不明白如何使用它...
不要在注释cascade = CascadeType.ALL中使用属性@OneToMany,而是使用 Hibernate 的@Cascade()注释,如下所示:
@OneToMany(orphanRemoval = true, mappedBy = "event")\n@Cascade({CascadeType.ALL})\nprivate Set<RecurrentRule> recurrentRules = new HashSet<>();\nRun Code Online (Sandbox Code Playgroud)\n\n因为cascade = CascadeType.ALL是一个 JPA 选项,所以当 Hibernate 会话尝试删除该对象时,它会搜索 Hibernate Cascade,但找不到它,这就是为什么你应该使用@Cascade.
要进一步阅读,请查看Cascade \xe2\x80\x93 JPA & Hibernate 注释常见错误,它给出了更好的解释。
\n| 归档时间: |
|
| 查看次数: |
2399 次 |
| 最近记录: |