Muki
Muki

Reputation: 3641

JPA 2.0 Foreign Key Constraint

I have simple OneToOne relationship:
Data <-> TherapyResult

I would like to express the following constraints with JPA.

  1. If a Data entity gets removed the associated TherapyResult should be delete,too
  2. If a TherapyResult entity gets removed the associated Data entity should remain in the db

The first constraint is really easy with JPA as I can add CascadingType.REMOVE

@OneToOne(cascade = { CascadeType.REMOVE, CascadeType.REFRESH })
private TherapyResult therapyResult;

For the second constraint I would like to add something like

@JoinColumn(columnDefinition = "DATA_ID BIGINT CONSTRAINT THERAPYRESULTDTAID FOREIGN KEY (DATA_ID) REFERENCES DATA (ID) ON DELETE SET NULL")

However this does not work. OpenJPA seems to have something similiar, but I want to use JPA 2.0 and EclipseLink. OpenJPA ForeignKey.

Another solution would be using @PreRemove described here, which works but looks a bit "none-best-practices" to me. However just a feeling.

My setup is: Eclipse 3.7.1 EclipseLink 2.3 Apache Derby 10.8.3 and/or HSQLDB

any help is appreciated, Muki

Upvotes: 1

Views: 3027

Answers (2)

JB Nizet
JB Nizet

Reputation: 692181

If you have a foreign key from Data to TherapyResult, and Data is the owner of the association, then

  • removing the Data will delete the TherapyResult automatically if cascade is set to REMOVE
  • you just need to set the therapyResult field to null and then delete the TherapyResult to have what you need. Another option is to set orphanRemoval to true, in which case setting the therapyResult field to null is sufficient to remove it from the database

If you have a foreign key from TherapyResult to Data, and TherapyResult is the owner of the association, then

  • removing the Data will delete the TherapyResult automatically if cascade is set to REMOVE on the Data.therapyResult field.
  • removing the TherapyResult will leave the Data in the DB provided the cascade is not set to REMOVE on the TherapyResult.data field

Upvotes: 2

DataNucleus
DataNucleus

Reputation: 15577

You can't use pure JPA to specify foreign keys ... that spec doesn't include the ability. JDO is the only standard with the ability to define FKs. You have to use implementation specifics, or just define the schema yourself and let the JPA impl run on it.

Upvotes: 2

Related Questions