본문 바로가기
Tips/Spring Boot

[Spring Boot] OSIV (Open Session In View) 비활성화 후 JPA 조회 안될 때

by DevJaewoo 2022. 9. 21.
반응형

OSIV (Open Session In View) 비활성화 후 JPA 조회 안될 때

기존에 잘 돌아가던 코드에서 OSIV를 비활성화하고 다시 돌려보니 아래와 같은 에러가 나며 Entity 조회가 되지 않았다.

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; 
nested exception is org.springframework.orm.jpa.JpaSystemException: could not advance using next(); 
nested exception is org.hibernate.exception.GenericJDBCException: could not advance using next()] with root cause

 

다른 코드는 다 잘 동작하는데, 아래의 코드와 같이 getResultStream을 사용하는 조회 코드들만 에러가 난다.

public Optional<File> findOneWithClient(Long id) {
    String jpql = "select f from File f left join fetch f.client where f.id = :id";
    return em.createQuery(jpql, File.class)
            .setParameter("id", id)
            .getResultStream().findAny();
}

 

찾아보니 JPA 버그로, Steam 관련 코드는 @Transactional을 붙여줘야 된다고 한다.

https://stackoverflow.com/questions/40775697/streaming-query-results-closes-prematurely-spring-data-jpa-and-hibernate

 

Streaming query results closes prematurely - Spring Data JPA and Hibernate

Here is a repository with the code in this question exibiting the bug: https://github.com/agsimeonov/stream-bug I have been attempting to stream query results with Spring Data JPA and Hibernate us...

stackoverflow.com

 

아래와 같이 Service의 조회 함수에 @Transactional(readOnly = true)를 붙여주면 해결된다.

@Transactional(readOnly = true)
public FileDTO findOneWithClient(Long id) {
    File file = fileRepository.findOneWithClient(id).orElseThrow(() -> new ItemNotFoundException(File.class, "ID: " + id));
    return new FileDTO(file);
}
반응형