JPA not generating “on delete set null” FK restrictions

前端 未结 5 584
[愿得一人]
[愿得一人] 2021-01-04 19:11

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 v

相关标签:
5条回答
  • 2021-01-04 19:39

    In your case, you are generating the database from the classes. This would imply that you wont use the database for other purposes (as doing so would force you to have DDL scripts). That means that have this rule implemented in the database or in the java code is unimportant.

    We also know that Hibernate would raise a transient exception in the case where one would delete one or more statuses and try to reference it when committing without a cascade.

    Also, the database will be generated using a foreign key constraint.

    All that means that the constraint MUST be respected for the application to work.

    If your entities are in a jar by themselves, you could add a transient method to the alarm or the status interface to remove a status while respecting the rule.

    Also, the programmers, when using the entities will be forced to respect the rule or else the code wont work. But to make the task easier, you could make the relation bidirectional so that the task of tracking down the alarms from the statuses is made easier.

    If you can, use an ondelete interceptor/listener to set the alarm.status property to null.

    0 讨论(0)
  • 2021-01-04 19:39

    Are you sure with your @OneToOne? It seems to me that you'd rather use @ManyToOne (as a status can be affected to several alarms):

    @Entity
    public class Alarm {
        ...
    
        @ManyToOne(cascade=CascadeType.ALL)
        @JoinColumn(name="idStatus", nullable=true)
        private Status status;
    
        ...
    }
    
    0 讨论(0)
  • 2021-01-04 19:41

    Don't know about other non-hibernate implementations, but here is a JIRA issue I've been following about this in Hibernate...

    http://opensource.atlassian.com/projects/hibernate/browse/HHH-2707

    0 讨论(0)
  • 2021-01-04 19:43

    OpenJPA has

    @ForeignKey(deleteAction=ForeignKeyAction.NULL)
    

    but there is no standard JPA way to do this (and apparently it is impossible with Hibernate).

    Makes me want to go back to JDO.

    0 讨论(0)
  • 2021-01-04 19:48

    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.

    0 讨论(0)
提交回复
热议问题