JPA 不生成“on delete set null"FK 限制 [英] JPA not generating "on delete set null" FK restrictions

查看:26
本文介绍了JPA 不生成“on delete set null"FK 限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相关的类 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 限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆