有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java DataAccessException无法强制转换为SQLException以获取错误代码和sql状态

下面的代码片段来自Spring5食谱手册(第386页)。我试图运行和测试代码,但得到了sqle变量的NullPointerException,而且在Spring5中SQLExceptionDataAccessException之间似乎没有关系。有人能告诉我为什么和怎么做吗

package com.apress.springrecipes.vehicle;
...
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;

public class Main {

    public static void main(String[] args) {
        ...
        VehicleDao vehicleDao = context.getBean(VehicleDao.class);
        Vehicle vehicle = new Vehicle("EX0001", "Green", 4, 4);
        try {
            vehicleDao.insert(vehicle);
        } catch (DataAccessException e) {
            SQLException sqle = (SQLException) e.getCause();
            System.out.println("Error code: " + sqle.getErrorCode());
            System.out.println("SQL state: " + sqle.getSQLState());
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    首先,您从不检查e.getCause()是否返回null。 如果它返回null,则代码易受NullPointerException攻击

    第二点是,为什么Spring会改变其处理数据库/jpa异常的方式。 已经有一些关于这方面的对话。例如LINK

    或者,您还可以进一步查看C.Walls的《Spring in Action》(Spring in Action)一书,在这本书中我们可以阅读到关于JDBC的章节

    (10.1.1了解Spring的数据访问异常层次结构)

    On one hand, JDBC’s exception hierarchy is too generic—it’s not much of a hierarchy at all. On the other hand, Hibernate’s exception hierarchy is proprietary to Hibernate. What we need is a hierarchy of data-access exceptions that are descriptive but not directly associated with a specific persistence framework.

    我强烈推荐整个分章来理解这个主题