본문 바로가기

Web/spring

[Spring Exception]Guide to Spring NonTransientDataAccessException

728x90

https://www.baeldung.com/nontransientdataaccessexception

 

 

 

 

막바지로 달려가는 중..

나중에 포스팅한거 정리 좀 해야겠다ㅜㅜ

 

NonTransientDataAccessException

 

 

 


The Base Exception Class

일시적이지 않거나 영구적인 데이터 액세스 관련 예외처리를 나타냄

이 예외가 발생되면 그 이후 해결할 때 까지 모든 시도를 실패하게 됨

 

Subclasses of this main exception class represent data access related exceptions which are considered non-transient or permanent.

Simply put, that means that – until the root cause is fixed – all future attempts of a method that caused an exception, will fail.

 

 


 

DataIntegrityViolationException

NonTransientDataAccessException 의 이 하위 유형은 데이터 수정 시도로 인해 무결성 제약 조건이 위반될 때 발생한다

 

name null 비허용 예시

@Column(nullable = false)
private String name;

이름 값을 설정하지 않고 인스턴스를 저장하려고 하면 DataIntegrityViolationException이 발생한다.

@Test(expected = DataIntegrityViolationException.class)
public void whenSavingNullValue_thenDataIntegrityException() {
    Foo fooEntity = new Foo();
    fooService.create(fooEntity);
}

 

 

 

DuplicateKeyException

DataIntegrityViolationException 의 하위 클래스 중 하나 는 DuplicateKeyException 인데,

이미 존재하는 기본 키 또는 unique constraint 조건이 있는 열에 이미 값이 있는데 저장하려는 경우 발생한다

 

@Test(expected = DuplicateKeyException.class)
public void whenSavingDuplicateKeyValues_thenDuplicateKeyException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    jdbcTemplate.execute("insert into foo(id,name) values (1,'a')");
    jdbcTemplate.execute("insert into foo(id,name) values (1,'b')");
}

 


DataRetrievalFailureException

 

데이터베이스에 존재하지 않는 식별자로 개체를 찾는 것과 같이 데이터를 검색하는 동안 문제가 나타날 때 발생한다

 

JdbcTemplate 클래스에서 예외를 발생시킨다

@Test(expected = DataRetrievalFailureException.class)
public void whenRetrievingNonExistentValue_thenDataRetrievalException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    
    jdbcTemplate.queryForObject("select * from foo where id = 3", Integer.class);
}

 

IncorrectResultSetColumnCountException

적절한 RowMapper를 생성하지 않고 테이블에서 여러 열을 검색하려고 시도할 때 발생

@Test(expected = IncorrectResultSetColumnCountException.class)
public void whenRetrievingMultipleColumns_thenIncorrectResultSetColumnCountException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);

    jdbcTemplate.execute("insert into foo(id,name) values (1,'a')");
    jdbcTemplate.queryForList("select id,name from foo where id=1", Foo.class);
}

 

IncorrectResultSizeDataAccessException

이 예외는 검색된 레코드 수가 예상한 것과 다를 때 발생한다

예를 들어 단일 Integer 값이 필요하지만 쿼리에 대해 두 개의 행을 검색하는 경우이다.

@Test(expected = IncorrectResultSizeDataAccessException.class)
public void whenRetrievingMultipleValues_thenIncorrectResultSizeException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);

    jdbcTemplate.execute("insert into foo(name) values ('a')");
    jdbcTemplate.execute("insert into foo(name) values ('a')");

    jdbcTemplate.queryForObject("select id from foo where name='a'", Integer.class);
}

 

 

 

DataSourceLookupFailureException

이 예외는 지정된 데이터 소스를 얻을 수 없을 때 발생한다. 

 

JndiDataSourceLookup 클래스를 사용하여 존재하지 않는 데이터 소스를 찾는 경우 이다.

@Test(expected = DataSourceLookupFailureException.class)
public void whenLookupNonExistentDataSource_thenDataSourceLookupFailureException() {
    JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);
    DataSource dataSource = dsLookup.getDataSource("java:comp/env/jdbc/example_db");
}

 

 

InvalidDataAccessResourceUsageException

사용자에게 SELECT 권한이 없는 경우와 같이 리소스에 잘못 액세스하면 이 예외가 발생시킨다 .

 

이 예외를 테스트하려면 사용자의 SELECT 권한을 취소한 다음 SELECT 쿼리를 실행하면 된다.

@Test(expected = InvalidDataAccessResourceUsageException.class)
public void whenRetrievingDataUserNoSelectRights_thenInvalidResourceUsageException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    jdbcTemplate.execute("revoke select from tutorialuser");

    try {
        fooService.findAll();
    } finally {
    	//finally 블록 에서 사용자에 대한 권한을 복원하고 있음
        jdbcTemplate.execute("grant select to tutorialuser");
    }
}

 

 

 

BadSqlGrammarException

InvalidDataAccessResourceUsageException의 자주 발생하는 일반적인 하위 유형으로

잘못된 SQL로 쿼리를 실행하려고 시도할 때 발생하는 BadSqlGrammarException이다 .

@Test(expected = BadSqlGrammarException.class)
public void whenIncorrectSql_thenBadSqlGrammarException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    jdbcTemplate.queryForObject("select * fro foo where id=3", Integer.class);
}

from 이 아니라 fro 라고 쿼리 날림..ㅎ

 

 

CannotGetJdbcConnectionException

이 예외는 JDBC를 통한 연결 시도가 실패할 때(예: 데이터베이스 URL이 올바르지 않은 경우) 발생한다. 

다음과 같이 URL을 작성하면

jdbc.url=jdbc:mysql:3306://localhost/spring_hibernate5_exceptions?createDatabaseIfNotExist=true

그런 다음 명령문 실행을 시도할 때 CannotGetJdbcConnectionException이 발생한다.

@Test(expected = CannotGetJdbcConnectionException.class)
public void whenJdbcUrlIncorrect_thenCannotGetJdbcConnectionException() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(restDataSource);
    jdbcTemplate.execute("select * from foo");
}
728x90