【问题标题】:Cascade All not deleting级联全部不删除
【发布时间】:2012-01-04 22:45:06
【问题描述】:

请检查此实体:

@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……为什么会发生这种情况?

【问题讨论】:

    标签: java jpa jpa-2.0


    【解决方案1】:

    这很正常。你没有删除 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。我还要补充一点,合并的调用是不必要的:实体已附加。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2015-04-24
    相关资源
    最近更新 更多