【问题标题】:Mybatis Spring Transactional multiple delete constraint violatedMybatis Spring Transactional 多次删除约束违反
【发布时间】:2014-05-30 12:06:42
【问题描述】:

我正在使用 Spring 3 和 Mybatis 3。

当我想进行级联删除时,一切正常。

我有 2 个带有中间 M-M 关系表的表。像 Table1 ---> MiddleTable ---> Table2

我想从中间表中删除,然后删除表2中的相关数据。

在使用事务方法时

@Transactional
public void relacionaReservaLibreBonoLibre(ParametrosRelacionReservaBono params) throws Exception{
    ReservaBean r=rm.buscarReservaPorPK(params.getReserva());


    for(BonoJson b:params.getListaBonosAdd()){
        HotelBean h=hm.buscaHotelPorCodHotel(b.getHotel());
        EstacionBean e=em.buscaEstacionPorEstacionYHotel(b.getEstacion(),h.getCnHotel());

        DocumentoBean db=new DocumentoBean();
        db.setCnEstacion(e.getCnEstacion());
        db.setCnHotel(h.getCnHotel());
        db.setCnTipDoc(r.getCnTipoDoc());
        db.setFlLibre(true);
        db.setTeDoc(b.getCodBono());
        Integer docId=dm.insertaDocumento(db);

        DocumentoReservaBean drb=new DocumentoReservaBean();
        drb.setCnDoc(docId);
        drb.setCnReserva(r.getCnReserva());

        drm.insertaDocumentoReserva(drb);
    }

    for(BonoJson b:params.getListaBonosQuit()){
        HotelBean h=hm.buscaHotelPorCodHotel(b.getHotel());
        EstacionBean e=em.buscaEstacionPorEstacionYHotel(b.getEstacion(),h.getCnHotel());


        ReservaDocumentoReservaBean filtro=new ReservaDocumentoReservaBean();
        filtro.setTeDoc(b.getCodBono());
        filtro.setCnReserva(r.getCnReserva());
        filtro.setFlLibre(true);
        List<ReservaDocumentoReservaBean> resPrev=rdm.getReservaDocumentos(filtro);

        for(ReservaDocumentoReservaBean resPart:resPrev){


            DocumentoReservaBean drb=new DocumentoReservaBean();
            drb.setCnDocReserva(resPart.getCnDocReserva());
            drm.eliminaDocumentoReservaPorPK(drb);

            DocumentoBean db=new DocumentoBean();
            db.setCnDoc(resPart.getCnDoc());
            dm.eliminaDocumentoPorPK(db);
        }
    }

}

在执行 de 时效果很好

dm.eliminaDocumentoPorPK(db);

它将违反约束的Table2启动到中间表,它应该被删除

drm.eliminaDocumentoReservaPorPK(drb);

¿任何提示?

提前致谢。

【问题讨论】:

    标签: spring transactions mybatis delete-row


    【解决方案1】:

    有几种选择:

    1. 从 Table2 中删除,然后从 MiddleTable 中删除
    2. 如果这是可接受的(即 MiddleTable 实体拥有 Table2 实体),则更改数据库中的外键,以便在删除 MiddleTable 中的行时通过级联删除 Table2 中的行。只需将 ON CASCADE DELETE 添加到 Table2 到 MiddleTable 定义的外键即可。
    3. 如果您的数据库支持,请延迟外键约束。

    【讨论】:

    • 第三个选项是我要找的,我忘了说 DB 是 PostgreSQL。谢谢
    猜你喜欢
    • 2019-01-02
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多