2011-11-23 103 views
3

請檢查該實體:級聯所有不刪除

@Entity 
@Table(name = "css_empresa") 
public class Empresa extends EntidadContactable implements Serializable, 
    Convert { 
private static final long serialVersionUID = 1L; 

@Id 
@SequenceGenerator(name = "EMPRESA_ID_GENERATOR", sequenceName = ConstantesSecuencias.SEQ_EMPRESA, allocationSize = 1) 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMPRESA_ID_GENERATOR") 
@Column(name = "cod_empresa", unique = true, nullable = false) 
private Long id; 


@Column(name = "num_ruc", precision = 13) 
private BigDecimal numRuc; 

@Column(name = "num_rup", precision = 15) 
private BigDecimal numRup; 

@Column(name = "txt_direccion_web", length = 255) 
private String txtDireccionWeb; 

@Column(name = "txt_nombre", nullable = false, length = 255) 
private String txtNombre; 

@Column(name = "txt_observaciones", length = 255) 
private String txtObservaciones; 

@OneToOne 
@JoinColumn(name = "cod_usuario") 
private Usuario administrador; 

// bi-directional many-to-one association to DireccionEmpresa 
@OneToMany(mappedBy = "empresa", fetch = FetchType.LAZY, cascade = CascadeType.ALL) 
private List<DireccionEmpresa> direccionEmpresas; 

    //Getters Setters ommited for brevity 
    } 

然後在我的控制器,我有這樣的事情:

Empresa empresa=entityManager.findById(1L); 
empresa.getDireccionEmpresas.remove(direccionEmpresa); 
entityManager.merge(empresa); 

但是這不會從數據庫中刪除DireccionEmpresa ......爲什麼這可能會發生?

回答

5

這很正常。你沒有刪除empresa,所以沒有什麼可以級聯的。您只從相應的集合中刪除direccionEmpresa。您必須手動刪除該對象。

another question on this topic這很好地解釋了這種情況。

JPA 2添加了orphanRemoval屬性,在從父集合中刪除子對象時應該注意刪除子對象。所以你的情況這將是:

@OneToMany(mappedBy = "empresa", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) 
private List<DireccionEmpresa> direccionEmpresas; 

//Getters Setters ommited for brevity 
} 
+1

+1。我還會補充說,合併調用是不必要的:實體被連接。 –