Java – JPA does not generate “on delete set null” FK restrictions

I have two related terms JPA notes Alarms and status An alarm can have a state

What I need is to be able to delete a state and "propagate" a null value to an alert in the deleted state

That is, I need to define the foreign key 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 (delete status with id = 2)

STATUS
id  description
1   new
3   closed

ALARMS
id  status
1   1
2   NULL
3   NULL

I use hibernate and PostgreSQL to automatically generate databases from source code I tried every possible cascadetype and failed

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

Solution

Just add a comment using Hibernate:

@OnDelete(action=OnDeleteAction.CASCADE)

The generated foreign key is "on update no action on delete cascade"; “

But no action = ondeleteaction SET_ NULL

In addition, I don't like binding code to hibernate if possible (but I can use it if it works)

This thread discusses it I can't believe there is no simple way to generate foreign keys in JPA (or hibernate extension)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>