JPA not generating quot;on delete set nullquot; FK restrictions(JPA 不生成“on delete set nullFK 限制)
问题描述
我有两个相关的类 JPA 注释.警报和状态.一个警报可以有一个状态.
I have two related clases JPA-annotated. Alarm and Status. One Alarm can have one Status.
我需要的是能够删除一个状态并将空值传播"到该状态中已删除的警报.
What I need is to be able to delete one Status and "propagate" a null value to the Alarms that are in that Status that has been deleted.
也就是说,我需要将外键定义为on delete set null".
That is, I need the foreign key to be defined as "on delete set null".
@Entity
public class Alarm {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sequence")
@SequenceGenerator(name="sequence", sequenceName="alarm_pk_seq")
private Integer id;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="idStatus")
private Status status;
// get/set
}
@Entity
public class Status {
@Id
@Column(name="idStatus")
private Integer id;
private String description;
// get/set
}
例子:
之前:
STATUS
id description
1 new
2 assigned
3 closed
ALARMS
id status
1 1
2 2
3 2
之后(删除 id=2 的状态)
After (deleting the status with id=2)
STATUS
id description
1 new
3 closed
ALARMS
id status
1 1
2 NULL
3 NULL
我正在使用 Hibernate 和 PostgreSQL,从源代码自动生成数据库.我尝试了所有可能的 CascadeType 都没有成功.
I am using Hibernate and PostgreSQL, automatically generating the database from source code. I have tried with every possible CascadeType with no success.
代码有什么问题吗?用 JPA 可以做到吗?
Is there anything wrong in the code ? Is it possible to do it with JPA ?
推荐答案
只需使用 Hibernate 注释添加即可:
Just add that using the Hibernate annotation:
@OnDelete(action=OnDeleteAction.CASCADE)
生成外键为:ON UPDATE NO ACTION ON DELETE CASCADE;"
generates the foreign key as : "ON UPDATE NO ACTION ON DELETE CASCADE;"
但是没有action=OnDeleteAction.SET_NULL
But there is no action=OnDeleteAction.SET_NULL
此外,如果可能的话,我不喜欢将我的代码绑定到 Hibernate(但如果它有效,我可以接受它).
Moreover, I don't like to tie my code to Hibernate if possible (but I can live with it if it works).
这个线程讨论了它.我不敢相信在 JPA(或 Hibernate 扩展)中没有一种简单的方法来生成外键.
This thread discusses it. I can't believe there is not an easy method in JPA (or Hibernate extensions) to generate the foreign key.
这篇关于JPA 不生成“on delete set null"FK 限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JPA 不生成“on delete set null"FK 限制


- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01