헤르메스 LIFE

[JPA] Query Modifying 의 사용 본문

Spring Boot Framework

[JPA] Query Modifying 의 사용

헤르메스의날개 2023. 6. 16. 02:36
728x90

NativeQuery 를 이용해서 삭제했는데, 아래와 같은 오류가 발생했습니다.

could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet


CommentRepository.java

package octopus.bbs.comment.repository;

import java.util.List;

import javax.persistence.Tuple;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import octopus.bbs.comment.dto.TCommentM;

// https://hackids.tistory.com/129 참조
//
// @Repository : JpaRepository를 사용하면 @Repository를 사용하지 않아도 됨.
public interface CommentRepository extends JpaRepository<TCommentM, Long> {
    
    String DELETE_BY_POSTID = "delete from t_comment_m a " +
            " where a.post_id = ?1";

    @Query(value = DELETE_BY_POSTID, nativeQuery = true)
    void deleteByPostId(Long postId);
}

DELETE를 실행하면 막상될 듯 하지만, 원하는 결과를 얻을 수 없습니다.

@Query 는 데이터베이스에서 읽기를 위한 쿼리를 실행합니다. 실제 Database 에 Update /  Delete 하지 않습니다. @Modifying Annotation 을 사용하면 Update Query로 트리거된다고 합니다.

CommentRepository.java

package octopus.bbs.comment.repository;

import java.util.List;

import javax.persistence.Tuple;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import octopus.bbs.comment.dto.TCommentM;

// https://hackids.tistory.com/129 참조
//
// @Repository : JpaRepository를 사용하면 @Repository를 사용하지 않아도 됨.
public interface CommentRepository extends JpaRepository<TCommentM, Long> {
    
    String DELETE_BY_POSTID = "delete from t_comment_m a " +
            " where a.post_id = ?1";

    @Modifying
    @Query(value = DELETE_BY_POSTID, nativeQuery = true)
    void deleteByPostId(Long postId);
}

https://docs.spring.io/spring-data/jpa/docs/1.4.2.RELEASE/reference/html/jpa.repositories.html#jpa.modifying-queries

 

2. JPA Repositories

MonetaryAmount amount = new MonetaryAmount(200.0, Currencies.DOLLAR); List customers = customerRepository.findAll( where(isLongTermCustomer()).or(hasSalesOfMoreThan(amount))); As you can see, Specifications offers some glue-code methods to chain and combin

docs.spring.io

 

728x90