2011-11-23 99 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。我还会补充说,合并调用是不必要的:实体被连接。 –