Java Reference
In-Depth Information
<property name="duplicateKeyCodes">
<value>23505</value>
</property>
<property name="dataIntegrityViolationCodes">
<value>22001,22005,23502,23503,23513,
➥
X0Y32</value>
</property>
<property name="dataAccessResourceFailureCodes">
<value>04501,08004,42Y07</value>
</property>
<property name="cannotAcquireLockCodes">
<value>40XL1</value>
</property>
<property name="deadlockLoserCodes">
<value>40001</value>
</property>
</bean>
</beans>
Note that the
databaseProductName
property is used to match the database product name returned
by
Connection.getMetaData().getDatabaseProductName()
. This enables Spring to know which type of
database is currently connecting. The
useSqlStateForTranslation
property means that the
SQLState
property, rather than the
errorCode
property, should be used to match the error code. Finally, the
SQLErrorCodes
class defines several categories for you to map database error codes. The code
23505
lies
in the
dataIntegrityViolationCodes
category.
Customizing Data Access Exception Handling
The Spring JDBC framework only maps well-known error codes. Sometimes you may wish to customize
the mapping yourself. For example, you might decide to add more codes to an existing category or
define a custom exception for particular error codes.
In Table 3-2, the error code
23505
indicates a duplicate key error in Apache Derby. It is mapped
by default to
DataIntegrityViolationException
. Suppose that you want to create a custom exception
type,
MyDuplicateKeyException
, for this kind of error. It should extend
DataIntegrityViolationException
because it is also a kind of data integrity violation error. Remember that for an exception to be thrown by
the Spring JDBC framework, it must be compatible with the root exception class
DataAccessException
.
package com.apress.springenterpriserecipes.vehicle;
import org.springframework.dao.DataIntegrityViolationException;
public class MyDuplicateKeyException extends DataIntegrityViolationException {
public MyDuplicateKeyException(String msg) {
super(msg);
}
public MyDuplicateKeyException(String msg, Throwable cause) {
super(msg, cause);
}
}
Search WWH ::
Custom Search