【发布时间】:2023-04-10 03:38:01
【问题描述】:
下面的 sn-p 代码来自 Spring 5 食谱书(第 386 页)。我正在尝试运行和测试代码,但得到 NullPointerException 的 sqle 变量,而且在 Spring 5 中,SQLException 和 DataAccessException 之间似乎没有任何关系。有人可以告诉我为什么以及如何操作吗?
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() 不是 SqlException 类型。您可以在执行强制转换操作之前打印所有堆栈跟踪或使用您的 IDE 对其进行调试。
-
你的
vehicleDaonull是吗?
标签: java spring sqlexception