[英]Spring JPA/Hibernate - OneToMany bi-directional problem
我遇到了這個讓我睡不着的問題
我有 2 個實體 Property 和 Tenant
每個屬性可以有 0..1 個租戶,每個租戶可以有 1..N 個屬性
// some annotations
public class Tenant {
// more fields
@OneToMany(mappedBy = "tenant", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private Set<Property> properties = new HashSet<>();
}
// some annotations
public class Property {
// more fields
@ManyToOne(fetch = FetchType.LAZY)
private Tenant tenant;
}
我想要完成的是當我創建一個新租戶時,使用級聯我想將它附加到現有屬性
保存是通過 JpaRepository.save(Tenant) 完成的
例如首先我創建新屬性
{
// more fields
"tenant": null
}
然后某個時候,我決定要為這個屬性創建一個租戶
{
// more fields
"properties": [
{
"id": 1, // property id I want to create this tenant for
"tenant": null
}
]
}
我相信我已經嘗試過每一種級聯類型(除了 ALL 和 PERSIST,這兩種不能與分離的實體一起使用)
如何將新創建的租戶與已經存在的屬性同步?
我讀到 CascadeType.MERGE 應該可以解決這個問題,但它不適合我
任何幫助表示贊賞提前謝謝
編輯:所有的 getter 和 setter 都是由 lombok 生成的
用於儲蓄的休息資源
@PostMapping
public ResponseEntity<Void> saveTenant(
@Valid @RequestBody TenantDto tenantDto, UriComponentsBuilder uriComponentsBuilder) {
log.info(tenantDto.toString());
Long id = tenantService.saveTenant(tenantDto);
URI location = uriComponentsBuilder.path("/api/tenants/{id}").buildAndExpand(id).toUri();
return ResponseEntity.created(location).build();
}
服務
@Override
public Long saveTenant(TenantDto tenantDto) {
// mapstruct mapping
return tenantRepository.save(tenantMapper.toEntity(tenantDto)).getId();
}
回購
@Repository
public interface TenantRepository extends JpaRepository<Tenant, Long> {}
級聯是當您有 2 個實體,並且您希望它們都被UPDATE
編輯 / INSERT
編輯 / 任何東西,即使您只明確地對其中一個做了什么。 您的問題與級聯無關 - 因為您想插入一個實體,但要更新另一個實體。
現在,您在Tenant.properties
上放置了mappedBy
。 這意味着Property
將是擁有實體 - 它負責保存這兩個實體之間的連接。
這意味着您需要從 DB 中檢索Property
並將Tenant
設置為它。 然后在保存Property
時,您將填寫您的外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.