![](/img/trans.png)
[英]How to filter an entity by multiple fields using a Spring JPA Repository?
[英]How to persist an entity with multiple fields of a single type using JPA?
背景:
我有一個抽象類MobileResource
,它包含三個字段,每個字段的類型為Site
。 這些字段可以並且經常包含相同的對象。
@Entity
public abstract class MobileResource extends Resource implements Serializable {
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Site homeSite;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Site currentSite;
@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST})
private Site relocationSite;
// constructors, getters, setters
}
我還有MobileResource
的Person
具體子類。
@Entity
public class Person extends MobileResource implements Serializable {
private String firstName;
private String surname;
// constructors, getters, setters
}
有問題的模塊是使用spring-data-jpa和postgres數據庫的spring-boot應用程序。 數據庫模式由spring / hibernate自動生成。
問題:
我試圖保留從外部REST資源檢索到的Person
的新實例。 當我使用彈簧引導注入的PersonRepository
擴展JpaRepository
並調用personRepository.save(person)
,出現以下異常:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-07 10:36:30,383 ERROR SpringApplication - Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
... 6 more
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fk_rmnbkmxocx4dcayhiyr1wxypc]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
... 23 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
... 56 more
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "person" violates foreign key constraint "fk_rmnbkmxocx4dcayhiyr1wxypc"
Detail: Key (current_site_id)=(738) is not present in table "site".
... 62 more
Person
欄 :
id [PK] | batch_id | brigade_id | call_sign | lat | lon | incident_id | type_id | current_site_id | home_site_id | relocation_site_id | status_id | first_name | surname
Site
欄:
id [PK] | batch_id | brigade_id | call_sign | lat | lon | location | type_id
題:
為了使持久性工作,應該進行哪些更改。 我的第一個假設是架構需要更改,但是我不確定它會以哪種方式執行,也不確定如何使用注釋來實現。
提前謝謝了。
編輯:只是為了澄清,我希望能夠在持久化Person
對象時持久化Site
對象,而不是預先持久化任何東西以准備Person
。
我曾經想到的一個方法是使用遠程服務器的主鍵( id
)作為備用鍵,並使用@GeneratedValue
生成我自己的鍵,但是我認為這也可能導致相同的問題。
有人知道為什么CascadeType.PERSIST
在這種情況下不起作用嗎?
似乎Site表中沒有ID = 738的行,因此您不能將該行插入到Person表中。
您應該首先嘗試將一行插入ID為738的Site表中,然后才嘗試將其插入到Person表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.