【问题标题】:How to handle org.hibernate.exception.ConstraintViolationException, I using try catch but it doesn't work如何处理 org.hibernate.exception.ConstraintViolationException,我使用 try catch 但它不起作用
【发布时间】:2019-08-06 14:31:35
【问题描述】:

此方法用于将数据保存在数据库中

public Response saveAll(PurchaseOrderHeaderDto purchaseOrderHeaderDto){
    try{
        s=sf.openSession();
        tx=s.beginTransaction();
        PurchaseOrderHeader orderDo=importDao(purchaseOrderHeaderDto);
        for(int i=0;i<orderDo.getPurchaseItemList().size(); i++){
            orderDo.getPurchaseItemList().get(i).setHeaderDetails(orderDo);
            s.save(orderDo.getPurchaseItemList().get(i));
        }
        response.setStatus(200);
        response.setMessage("succesfull");
        tx.commit();

    }
    catch(ConstraintViolationException  e){
    System.out.println(e.getMessage());
        response.setStatus(500);
        response.setMessage("unsuccesfull");
        tx.rollback();

    }
    finally{
        s.close();
    }
    return response;
}

I am getting this error

 Error during managed flush [org.hibernate.exception.DataException: could not execute statement]

我不知道如何处理这个异常(我知道这是因为长度,但我想处理这个异常。欢迎提出任何建议)

【问题讨论】:

    标签: mysql spring hibernate rest


    【解决方案1】:

    因为您在获取DataException 时试图捕捉ConstraintViolationException。 尝试使用以下代码:

    public Response saveAll(PurchaseOrderHeaderDto purchaseOrderHeaderDto) {
        try {
            s = sf.openSession();
            tx = s.beginTransaction();
            PurchaseOrderHeader orderDo = importDao(purchaseOrderHeaderDto);
            for (int i = 0; i < orderDo.getPurchaseItemList().size(); i++) {
                orderDo.getPurchaseItemList().get(i).setHeaderDetails(orderDo);
                s.save(orderDo.getPurchaseItemList().get(i));
            }
            response.setStatus(200);
            response.setMessage("succesfull");
            tx.commit();
    
        } catch (Exception e) {
            System.out.println(e.getMessage());
            response.setStatus(500);
            response.setMessage("unsuccesfull");
            tx.rollback();
    
        } finally {
            s.close();
        }
        return response;
    }
    

    这将捕获每个异常,您可能希望稍后再处理它,但它应该可以工作

    【讨论】:

    • 这会起作用,但我想抓住导致错误的列...我应该怎么做...欢迎任何建议
    • 不会有ConstraintViolationException 因为Hibernate 只是出于这个原因使用DataException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多