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 限制


基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01