Java Reference
In-Depth Information
package com.apress.springenterpriserecipes.vehicle;
...
public class Main {
public static void main(String[] args) {
...
VehicleDao vehicleDao = (VehicleDao) context.getBean("vehicleDao");
Vehicle vehicle = new Vehicle("EX0001", "Green", 4, 4);
vehicleDao.insert(vehicle);
}
}
If you run the method twice, or the vehicle has already been inserted into the database, it will throw
a DuplicateKeyException , a subclass of DataAccessException . In your DAO methods, you neither need to
surround the code with a try/catch block nor declare throwing an exception in the method signature.
This is because DataAccessException (and therefore its subclasses, including DuplicateKeyException ) is
an unchecked exception that you are not forced to catch. The direct parent class of DataAccessException
is NestedRuntimeException , a core Spring exception class that wraps another exception in a
RuntimeException .
When you use the classes of the Spring JDBC framework, they will catch SQLException for you and
wrap it with one of the subclasses of DataAccessException . As this exception is a RuntimeException , you
are not required to catch it.
But how does the Spring JDBC framework know which concrete exception in the DataAccessException
hierarchy should be thrown? It's by looking at the errorCode and SQLState properties of the caught
SQLException . As a DataAccessException wraps the under-lying SQLException as the root cause, you can
inspect the errorCode and SQLState properties with the following catch block:
package com.apress.springenterpriserecipes.vehicle;
...
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
public class Main {
public static void main(String[] args) {
...
VehicleDao vehicleDao = (VehicleDao) context.getBean("vehicleDao");
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());
}
}
}
Search WWH ::




Custom Search