Spring 操作数据库
Spring 会将数据操作的异常转换为 DataAccessException,这样我们就不需要去强制捕获异常,如果在使用SQL语句的时候出现异常,Sprig能抛出内置的特定异常。
无论使用何种数据访问方式,都能使用一样的异常
定制错误码解析逻辑
在spring中,我们可以在sql-error-codes.xml中编写我们制定的异常。以h2数据库为例:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="H2" class="org.springframework.jdbc.support.SQLErrorCodes">
<property name="badSqlGrammarCodes">//系统定制
<value>42000,42001,42101,42102,42111,42112,42121,42122,42132</value>
</property>
<property name="duplicateKeyCodes">//系统定制
<value>23001,23505</value>
</property>
<property name="dataIntegrityViolationCodes">//系统定制
<value>22001,22003,22012,22018,22025,23000,23002,23003,23502,23503,23506,23507,23513</value>
</property>
<property name="dataAccessResourceFailureCodes">//系统定制
<value>90046,90100,90117,90121,90126</value>
</property>
<property name="cannotAcquireLockCodes">//系统定制
<value>50200</value>
</property>
<property name="customTranslations"> //自己定制
<bean class="org.springframework.jdbc.support.CustomSQLErrorCodesTranslation">
<property name="errorCodes" value="23001,23505" />
<property name="exceptionClass"
value="geektime.spring.data.errorcodedemo.CustomDuplicatedKeyException" />
</bean>
</property>
</bean>
</beans>
具体实现代码如下:
package geektime.spring.data.errorcodedemo;
import org.springframework.dao.DuplicateKeyException;
public class CustomDuplicatedKeyException extends DuplicateKeyException {
public CustomDuplicatedKeyException(String msg) {
super(msg);
}
public CustomDuplicatedKeyException(String msg, Throwable cause) {
super(msg, cause);
}
}
package geektime.spring.data.errorcodedemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ErrorCodeDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ErrorCodeDemoApplication.class, args);
}
}
package geektime.spring.data.errorcodedemo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ErrorCodeDemoApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test(expected = CustomDuplicatedKeyException.class)//期望某种异常,如果没有指定的异常,会测试不通过
public void testThrowingCustomException() {
jdbcTemplate.execute("INSERT INTO FOO (ID, BAR) VALUES (1, 'a')");
jdbcTemplate.execute("INSERT INTO FOO (ID, BAR) VALUES (1, 'b')");
}
}
执行ErrorCodeDemoApplicationTests 后,我们可以看到如下结果:
这说明,我们已经抛出期望的异常。