我正在使用 Java、Spring 和 JPA,無法讓級聯洗掉作業。
我有一個看起來像這樣的類租戶
@Entity
@Validated
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TenantConstraints
public class Tenant {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tenant_gen")
@SequenceGenerator(name="tenant_gen", sequenceName="tenant_seq", allocationSize=1)
@JsonProperty("id")
private Long id = null;
@JsonIgnore
@OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER)
private List<DeploymentStep> deploymentSteps = new ArrayList();
...
}
我的 DeploymentStep 類如下所示:
@Entity
@Validated
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeploymentStep {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "deployment_step_gen")
@SequenceGenerator(name="deployment_step_gen", sequenceName="deployment_step_seq", allocationSize=1)
@JsonProperty("id")
private Long id = null;
@ManyToOne(cascade = CascadeType.ALL)
@JsonIgnore
private Tenant tenant = null;
...
}
我有一個看起來像這樣的存盤庫類
public interface TenantRepository extends JpaRepository<Tenant, Long> {
...
}
當我像這樣呼叫此存盤庫上的內置洗掉方法tenantRepository.delete(tenantId)并且我有針對要洗掉的特定租戶的部署步驟時,洗掉失敗。
在我的 postgres 資料庫中,我有一個級聯約束集
ALTER TABLE public.deployment_step
DROP CONSTRAINT tenant_fkey
, ADD CONSTRAINT tenant_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenant(id) ON DELETE CASCADE;
當我使用資料庫查詢手動洗掉具有部署步驟的租戶時,租戶和所有部署步驟都會被洗掉而沒有任何問題。
我在代碼中做錯了什么?
uj5u.com熱心網友回復:
您有級聯,DeploymentStep但您正在洗掉Tenant. 要洗掉DeploymentStep使用,TenantRepository您應該將級聯放在Tenant物體中。
@Entity
@Validated
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TenantConstraints
public class Tenant {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tenant_gen")
@SequenceGenerator(name="tenant_gen", sequenceName="tenant_seq", allocationSize=1)
@JsonProperty("id")
private Long id = null;
@JsonIgnore
@OneToMany(mappedBy = "tenant", fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<DeploymentStep> deploymentSteps = new ArrayList();
...
}
uj5u.com熱心網友回復:
租戶多方是錯誤的,它錯過了級聯規范。
https://docs.oracle.com/javaee/6/api/javax/persistence/OneToMany.html#cascade()
默認為沒有級聯操作。
JPA 沒想到 DeploymentSteps 會消失并回滾事務。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519435.html
