【问题标题】:About Spring Transaction Manager关于 Spring 事务管理器
【发布时间】:2012-03-28 20:31:51
【问题描述】:

目前我在我的应用程序中使用 spring 声明式事务管理器。在数据库操作期间,如果违反任何约束,我想检查数据库的错误代码。我的意思是我想在异常发生后运行一个选择查询。所以我在我的 Catch 块中捕获了 DataIntegrityViolationException,然后我试图再执行一个错误代码查询。但是那个查询没有被执行。我假设因为我正在使用事务管理器,如果发生任何异常,下一个查询不会被执行。那正确吗?。我想在将结果返回给客户端之前执行该错误代码查询。有什么办法吗?

@Override
@Transactional
    public LineOfBusinessResponse create(
        CreateLineOfBusiness createLineOfBusiness)
        throws GenericUpcException {
        logger.info("Start of createLineOfBusinessEntity()");


        LineOfBusinessEntity lineOfBusinessEntity =
            setLineOfBusinessEntityProperties(createLineOfBusiness);
        try {
            lineOfBusinessDao.create(lineOfBusinessEntity);
            return setUpcLineOfBusinessResponseProperties(lineOfBusinessEntity);

        }
        // Some db constraints is failed
        catch (DataIntegrityViolationException dav) {

            String errorMessage =
                errorCodesBd.findErrorCodeByErrorMessage(dav.getMessage());
            throw new GenericUpcException(errorMessage);
        }
        // General Exceptions handling
        catch (Exception exc) {
            logger.debug("<<<<Coming inside General >>>>");
            System.out.print("<<<<Coming inside General >>>>");
            throw new GenericUpcException(exc.getMessage());
        }

    }

public String findErrorCodeByErrorMessage(String errorMessage)throws GenericUpcException {
        try{
        int first=errorMessage.indexOf("[",errorMessage.indexOf("constraint"));
        int last=errorMessage.indexOf("]",first);
        String errorCode=errorMessage.substring(first+1, last);
        //return errorCodesDao.find(errorCode);
        return errorCode;
        }
        catch(Exception e)
        {
            throw new GenericUpcException(e.getMessage());
        }


    }

请帮帮我。

【问题讨论】:

    标签: spring transactions


    【解决方案1】:

    我认为您描述的问题与事务管理无关。如果DataIntegrityViolationException 发生在您的try() 块中,您应该执行catch() 中的代码。可能发生与DataIntegrityViolationException 不同的异常,或者您的findErrorCodeByErrorMessage() 抛出另一个异常。通常,只有在您从方法调用返回时才会应用事务逻辑,在此之前您可以使用普通的 Java 语言结构做任何您喜欢的事情。我建议您在错误错误处理程序或一些调试语句中设置断点以查看实际发生的情况。

    【讨论】:

    • 感谢您的回复。如果我使用@transaction 注释,它甚至不会在异常出现后点击 catch 块。它直接从数据库中给出错误字符串。它不允许我捕捉到错误。如果我不使用事务注释一切正常。而且我确信我的 findErrorCodeByErrorMessage() 方法没有问题。无论如何,我发布了我的 findErrorCodeByErrorMessage() 方法代码。请帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多