我遇到了這個讓我睡不著的問題
我有 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> {}
uj5u.com熱心網友回復:
級聯是當您有 2 個物體時,您希望它們都被UPDATEed / INSERTed / 任何東西,即使您只明確地對其中一個物體做了什么。您的問題與級聯無關 - 因為您想插入一個物體,但要更新另一個物體。
現在,你mappedBy在Tenant.properties. 這意味著Property它將成為擁有物體 - 它負責保存這兩個物體之間的連接。
這意味著您需要Property從資料庫中檢索并設定Tenant它。然后在保存時,Property您將填寫外鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490051.html
