HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/
Spring Data
Spring Data
/
🧣
JPA(Java Persistence API)
/
[Access Strategies] DB row→ entity 매핑 방법

[Access Strategies] DB row→ entity 매핑 방법

참고 : Access strategies in jpa and hibernate

Field-based access(추천)

  • reflection을 이용하여 entity의 attribute에 읽거나 쓰게 됨
  • 장점
    • 코드 가독성이 더 좋음
    • application에 의해 호출되지 않는 getter나 setter를 생략할 수 있음
    • getter나 setter메서드의 구현이 더 유연함
    • 유틸리티성 메서드에 대해 @Transient를 붙일 필요가 없음 (field based access에서는 persistence state가 entity의 attribute에 의해 정의되기 때문에)
    • proxy를 이용한 lazy fetch를 진행할 때, property-based access면 getter method만 불리어도 proxy object의 attribute를 다 초기화 해버림(하이버네이트가)

Property-based access

  • attribute들에 대해 getter method들이 필요함
 

Default configuration of access strategy

  • @Id annotation을 필드에 붙이면 default로 Field-based access를 사용하고
  • @Id annotation을 getter에 붙이면 property-based access로 작동하게 됨

Override the default access strategy

  • 하나의 엔티티에서 두개의 전략을 섞어서 사용하고 싶다면 @Access 어노테이션을 이용하기
 
@Entity public class Review { @Id protected Long id; /* ... */ }
@Entity public class Review { protected Long id; private Rating rating; private ZonedDateTime postedAt; private int version; @Id public Long getId() { return id; }
@Entity public class Review { protected Long id; private Rating rating; private ZonedDateTime postedAt; @Version @Access(AccessType.FIELD) private int version; @Id public Long getId() { return id; }
version attribute에 대해 property-based → field-based로 변경한 것임