💻
Albert's Til
GitHub
  • 매일매일 조금씩 성장하기
    • README
    • CS
      • Network
      • HTTP
        • NO-CACHE
      • 오류 코드
      • ORM 도구
      • Design Pattern
        • CQRS Pattern
          • Event Sourcing and CQRS pattern
        • Builder Pattern
    • DB
      • MySQL
        • Timeline
        • Pagination
        • Index
        • Database Performance Optimization Strategies
        • B+ tree
        • MySQL Connectors VS MySQL Shell(Scripting) VS MySQL Workbench
        • MySQL Storage Engine Architecture
      • Normalization & Denormalization
      • JPA
        • @Transactional
        • Why JPA?
        • About JPA
        • N+1 Issue
        • Index
        • ElementCollection&CollectionTable
        • orphanRemoval
        • CascadeType
        • Use Subselect
        • Dynamic Instance Creation
        • Paging
        • Order
        • Spefication
        • mappedBy
      • MongoDB
        • ObjectId
      • Why MySQL?
      • ACID properties of transactions
      • Between JPA and JDBC
      • Identifiers in Hibernate/JPA
    • Java
      • Jackson de/serialize
      • Collections.singletonList() vs List.of()
      • Manage dependencies in Gradle
      • Logging Level
      • Bean Validation
      • JVM Internals
        • Threads
          • Frame
        • Shared Between Threads
          • Classloader
            • Class Loader Hierarchy
            • Loading Linking Initialization
      • Java Collection Framework
      • Annotation
      • Generic
      • 디미터 법칙
    • Spring
      • Caching
      • Spring Integration Overview
        • ThreadPollTaskExecutor
        • Messaging Bridge
        • Channel Adapter
        • Poller
        • Configuration and @EnableIntegration
        • Message Endpoints
        • Message Channels
      • HATEOAS
      • @Autowired vs Constructor Dependency Injection
      • Spring Security
        • JWT 토큰 사용한 인가
        • OAuth 2 Login
        • OAuth 2 인증
        • 인가
        • 인증
        • PasswordEncoder
      • IoC Container
      • Filter,Interceptor,AOP,Argument Resolver
      • Spring Annotation
      • About Spring
    • Kafka
      • Error Channel
    • Infra
      • Scale Up || Scale Out
      • Docker
        • Dockerfile
        • Docker Hub Deploy
        • Command
      • Cloud 유형
        • Infrastructure as a Service
        • Platform as a Service
        • Software as a Service
      • 무중단 배포
        • 엔진엑스(Nginx)
      • 코드 자동 배포
        • Technical
      • AWS EC2
        • PEM(Privacy Enhanced Mail) 키
      • AWS RDS
      • AWS S3
    • CodeSquad
      • Spring Boot Project 1주차 회고
      • Spring Boot Project 2주차 회고
      • Spirng Boot Project 3주차 회고
      • Spring Boot Project 4주차 회고
    • Foody Moody 프로젝트
      • Query Performance Comparison
      • HeartCount Asynchronous Issue
      • DeferredResult
      • ResponseBodyEmitter
      • SseEmitter (Spring)
      • Server-Sent Events (SSE)
      • 기술 스택 적용 이유
      • NO-CACHE(HTTP)
      • Transactional
    • DDD
      • AggregateId
    • Test
      • RestAssured
    • Coding and Algorithmic Problems
      • 819. Most Common Word
      • 344. Reverse String
      • 125. Valid Palindrome
      • 937. Reorder Data in Log Files
    • Node
      • Async... Await...
      • Custom Transactional Decorator Challenger
    • Python
      • Python Basic Grammar
        • Comments and Input/Output
        • Variable
        • Data type
        • Operations and syntax
        • List,Tuple,Dictionary,Set
        • Function
        • Conditional statement
        • Loop
    • HTML
      • HTML Basic
      • HTML Basic Tags
      • HTML Form Tags
      • HTML Table Tags
    • CSS
      • CSS Basic
      • CSS Practice
Powered by GitBook
On this page
  • @Subselect
  • @immutable
  • @Synchronize
  • 적용
  • 문제
  • 원인
  • Reference

Was this helpful?

  1. 매일매일 조금씩 성장하기
  2. DB
  3. JPA

Use Subselect

하이버네이트 @Subselect 사용

@Immutable,@Subselcet,@Synchronize는 하이버네이트 전용 애너테이션이며 이 테그를 사용하면 테이블이 아닌 쿼리를 결과를 @Entity로 매핑할 수 있다.

@Subselect

@Subselect는 죄회(select) 쿼리를 값으로 갖는다. 하이버네이트는 이 select 쿼리의 결과를 매핑할 테이블처럼 사용한다. DBMS가 여러 테이블을 조인해서 조회한 결과를 한 테이블처럼 보여주기 위한 용도로 뷰를 사요하는 것 처럼 @Subselect를 사용하면 쿼리 실행 결과를 매핑 할 테이블처럼 사용한다

@immutable

@Immutabl을 사용하면 하이버네이트는 해당 앤티티의 매핑 필드/프로퍼티가 변경되도 DB에 반영하지 않고 무시한다.

  • @Subselct를 이용한 @Entity의 매핑 필드를 수정하면 하이버네이트는 변경 내역을 반영하는 update 쿼리를 실행할 것이다. 그런데 매핑 한 테이블이 없으므로 에러가 발생한다. 이런 문제를 방지하기 위해 사용한다.

@Synchronize

@Synchronize는 해당 엔티티와 관련된 테이블 목록을 명시한다. 하이버네이트는 엔티티를 로딩하기 전에 지정한 테이블과 관련된 변경이 발생하면 플러시(flush)를 먼저 한다.

  • 특별한 이유가 없으면 하이버네이트는 트랜잭션을 커밋하는 시점에 변경사항을 DB에 반형하므로 변경 내역을 아직 반영하지 않은 상태에서 조회하면 최신 값이 아닌 이전 값이 담기게 된다.

적용

문제

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Immutable
@Subselect("""
        select
             o.order_id,
             o.store_id as store_id,
             p.product_id as product_id,
             o.user_id as user_id,
             o.created_time,
             u.nickname as nickname,
             p.product_name,
             o.delivery_status,
             o.amount
        from
             order_products_id opi
                 left join purchase_order o
             on  o.order_id = opi.order_order_id
                 left join user u
             on o.user_id = u.user_id
                 left join product p
             on opi.product_id = p.product_id
        """
)
@Synchronize({"purchase_order", "order_products_id", "product","user"})
public class OrderData {
}

테스트 결과는 동일한 결과를 list로 return 받았다.

MySql 동일한 Query로 조회 결과 Product_id는 다르다.

원인

StoreID를 PK로 정하여 하이버네이트는 동일한 data로 판단하여 DB를 조회하지 않고 영속성 컨텍스트에서 객체를 가져와서 발생한 문제다.

Reference

Last updated 1 year ago

Was this helpful?

도메인 주도 개발 시작하기: DDD 핵심 개념 정리부터 구현까지