研究ノート@斗斗Spring全家斗
コースの内容は、Spring Family Bucketをプレイしているオタクの時間からのもので、侵入されて削除されました。リンクは次のとおりです。
https://time.geekbang.org/course/intro/100023501
四日目
春の異常な抽象化
DataAccessException
Spring
は、使用されているデータアクセス方法に関係なく、データ操作の例外をDataAccessExceptionsに変換します。同じ例外を使用できます。
Springはこれらのエラーコードをどのように認識しますか?
SQLErrorCodeSQLExceptionTranslatorクラス
を介してエラーコードを解析し、その中の各データベースのErrorCodeを定義します。
•org / springframework / jdbc / support/sql-error-codes.xml
•クラスパス下的sql-error-codes.x
サンプルコード:/resources/sql-error-codes.xmlファイル
<?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>
DuplicateKeyException例外クラス
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);
}
}
ErrorCodeDemoApplicationTestsテストクラス
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')");
}
}
テストクラスでは、目的の例外がDuplicateKeyExceptionクラスであり、結果が渡されることがわかります。
スローされた例外がDataAccessExceptionのサブクラスである限り、Springはエラーを報告し、例外をスローできません。