下面的代码片段来自 Spring 5 Recipes 书(第 386 页)。我正在尝试运行和测试代码,但得到 sqle
变量的 NullPointerException
,并且进一步看来 SQLException
和 DataAccessException 之间没有关系
在 Spring 5 中。有人能告诉我原因和方式吗?
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());
}
}
}
最佳答案
首先,你永远不会检查 e.getCause() 是否返回 null。 如果它返回 null,则您的代码很容易出现 NullPointerException
第二点是,为什么Spring改变它处理数据库/jpa异常的方式。 已经有一些关于此的讨论。例如LINK
或者您可以进一步查看 C. Walls 所著的“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.
我强烈推荐整个子章节来理解这个主题。
关于java - DataAccessException 无法转换为 SQLException 以获取错误代码和 sql 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802575/