我有兩個域對象,像這樣:無法刪除JPA實體是一個@ManyToOne關係的一部分
@Entity
public class Employee {
@Id
@Column(nullable = false, name = "id")
protected Integer id;
// Note: org_id is just an integer column in the database
@JoinColumn(nullable = true, name = "org_id")
@ManyToOne(targetEntity = Org.class)
private Org org;
}
...和:
@Entity
public class Org {
@Id
@Column(nullable = false, name = "id")
protected Integer id;
}
我來在我的邏輯中,我需要對數據庫中實際保存的內容進行重大更改。即某些組織正在被刪除,並且其中的員工正在重新分配。
我的問題是我的程序邏輯目前執行以下操作:
- 刪除需要通過
org.springframework.data.repository.delete(Iterable<? extends T> itrbl)
- 要刪除任何員工刪除需要通過
org.springframework.data.repository.delete(Iterable<? extends T> itrbl)
- 要刪除的任何機構]通過
org.springframework.data.repository.save(Iterable<S> itrbl)
- 創建新/更新現有的組織
org.springframework.data.repository.save(Iterable<S> itrbl)
問題涉及約在步驟2中我得到這樣一個例外:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException:對象引用一個未保存 例如瞬時 - 保存在 flushing之前的瞬態實例:com.sample.domain.Employee.org - > com.sample.domain.Org; 嵌套的例外是java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException:對象引用一個未保存 例如瞬時 - 前 沖洗保存瞬態的實例:com.sample.domain.Employee.org - > com.sample.domain .Org
如果組織沒有員工,我不想刪除組織。同樣,如果組織的員工被刪除,我不希望該組織被刪除。
我基本上只是想東西是一樣的,我是怎麼在PostgreSQL的外鍵設置在employees
表:
CONSTRAINT fk_employees_org_id FOREIGN KEY (org_id)
REFERENCES public.orgs (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE SET NULL
我已經看過了級聯選項,我不確定它是適用的,因爲它不是直的父母/子女關係(並且Employee
定義@ManyToOne
關係不是真正的父母 - 它是孩子),它不是雙向的(不需要組織擁有一個列表其所有員工)
你不想要級聯,因爲你已經說過自己不想刪除相關對象。因此,如果需要刪除一個Org,但仍然有一個FK指向它,那麼只需清除「員工」中的Org鏈接...刪除Org的前一個。 –
@NeilStockton - 謝謝,這只是我需要的指針(一直盯着這個問題太長時間纔看到明顯的!)。如果你想發表你的評論作爲答案,我會很樂意接受它。 – Catchwa