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

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

问题描述

我有两个相关的类JPA注释。报警和状态。一个警报可以有一个状态。



我需要的是能够删除一个状态,并且将一个空值传播到处于该状态的警报被删除。

也就是说,我需要将外键定义为删除集合null

  @Entity 
public class Alarm {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator =序列)
@SequenceGenerator(name =sequence,sequenceName =alarm_pk_seq)
private Integer id;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name =idStatus)
私有状态状态;
$ b $ //获取/设置
}

@实体
公共类状态{
@Id
@Column(name =idStatus)
私人整数ID;

私有字符串描述;

// get / set
}

示例: / b>

之前:

 状态
ID描述
1新增
2已分配
3已结算

警报
id身份
1 1
2 2
3 2

之后(删除id = 2的状态)

  STATUS 
id说明
1新
3已结算

警报
身份
1 1
2 NULL
3 NULL

我自动使用Hibernate和PostgreSQL从源代码生成数据库。我已经尝试过所有可能的CascadeType但没有成功。



代码中有什么错误吗?是否有可能用JPA做到这一点?

解决方案

只要添加使用Hibernate注释:

  @OnDelete(action = OnDeleteAction.CASCADE)

产生的外键为:ON UPDATE NO ACTION DELETE CASCADE;

但是没有动作= OnDeleteAction.SET_NULL



另外,如果可能,我不喜欢将代码绑定到Hibernate上(但是如果可以的话,我可以用它)。 >这个线程讨论它。我不能相信在JPA(或Hibernate扩展)中没有简单的方法来生成外键。


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.

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
}

Example:

Before:

STATUS
id  description
1   new
2   assigned
3   closed

ALARMS
id  status
1   1
2   2
3   2

After (deleting the status with id=2)

STATUS
id  description
1   new
3   closed

ALARMS
id  status
1   1
2   NULL
3   NULL

I am using Hibernate and PostgreSQL, automatically generating the database from source code. I have tried with every possible CascadeType with no success.

Is there anything wrong in the code ? Is it possible to do it with JPA ?

解决方案

Just add that using the Hibernate annotation:

@OnDelete(action=OnDeleteAction.CASCADE)

generates the foreign key as : "ON UPDATE NO ACTION ON DELETE CASCADE;"

But there is no action=OnDeleteAction.SET_NULL

Moreover, I don't like to tie my code to Hibernate if possible (but I can live with it if it works).

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天全站免登陆