평소에 Spring Data JPA 를 썼는데, 김영한님은 JPA 자체를 강의하시더라구요.
김영한님 강의 바탕으로 Spring Data JPA로 강의 소스를 테스트해보고 개념을 기록하기 위해 포스팅을 하게되었습니다.
고급 매핑
1. 상속관계 매핑
관계형 데이터베이스는 상속 관계X
슈퍼타입 서브타입 관계라는 모델링 기법이 객체 상속과 유사
상속관계 매핑: 객체의 상속과 구조와 DB의 슈퍼타입 서브타입 관계를 매핑
슈퍼타입 서브타입 논리 모델을 실제 물리 모델로 구현하는 방법
각각 테이블로 변환 -> 조인 전략
통합 테이블로 변환 -> 단일 테이블 전략
서브타입 테이블로 변환 -> 구현 클래스마다 테이블 전략
테이블은 여러개의 모델링이 나오지만, 객체는 상속관계라는 1개의 개념이다.
객체관계는 같지만 DB설계를 다르게 할 수 있음
관계형 데이터베이스는 상속 관계 X
슈퍼타입 서브타입 관계라는 모델링 기법이 객체 상속과 유사
상속관계 매핑 : 객체의 상속, 구조와 DB의 슈퍼타입 서브타입 관계를 매핑
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorColumn
@Getter
public abstract class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Book")
public class Book extends Item {
private String author;
private String isbn;
@Builder
public Book(String name, int price, String author, String isbn) {
super(name, price);
this.author = author;
this.isbn = isbn;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Album")
public class Album extends Item{
private String artist;
@Builder
public Album(String name, int price, String artist) {
super(name, price);
this.artist = artist;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Movie")
public class Movie extends Item {
private String actor;
private String director;
@Builder
public Movie(String name, int price, String actor, String director) {
super(name, price);
this.actor = actor;
this.director = director;
}
}
[Repository 코드]
public interface ItemRepository<T extends Item> extends JpaRepository<T, Long> {}
public interface BookRepository extends JpaRepository<Book, Long> {}
public interface AlbumRepository extends JpaRepository<Album, Long> {}
public interface MovieRepository extends JpaRepository<Movie, Long> {}
이때 ItemRepository extends 를 꼭 기억하자!! [abstract class jpaRepository 상속법]
ItemRepository만 사용해도 Book, Album, Movie를 모두 가져올 수 있다. (type casting 사용해서)
[테스트 코드]
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ItemTest {
@Autowired
ItemRepository itemRepository;
@Autowired
EntityManager entityManager;
@Before
public void setUp() throws Exception {
Movie movie = Movie.builder()
.actor("맷데이먼")
.director("리들리스콧")
.name("마션")
.price(10000)
.build();
Book book = Book.builder()
.author("조영호")
.isbn("isbn")
.name("객체지향의 사실과 오해")
.price(10000)
.build();
Album album = Album.builder()
.artist("엔플라잉")
.name("야호")
.price(30000)
.build();
itemRepository.save(movie);
itemRepository.save(book);
itemRepository.save(album);
entityManager.clear();
}
@Test
public void Item의_서브클래스_객체들_casting으로_가져오기() {
Movie movie = (Movie) itemRepository.findAll().get(0);
Book book = (Book) itemRepository.findAll().get(1);
Album album = (Album) itemRepository.findAll().get(2);
assertThat(movie.getName()).isEqualTo("마션");
assertThat(book.getName()).isEqualTo("객체지향의 사실과 오해");
assertThat(album.getArtist()).isEqualTo("엔플라잉");
}
}
@DiscriminatorColumn(name = "DTYPE") = default: DTYPE DTYPE이라는 Column이 super class의 table에 생기고, DTYPE의 값은 sub class의 이름으로 지정된다. SingleTable 전략에서 없어도 DTYPE 이생성되기도 하는데, 그래도 운영상 써주자
@DiscriminatorValue("XXX") = default: classname
[예시]
@Inheritance(strategy = InheritanceType.JOIN)
@DiscriminatorColumn(name = "DTYPE")
public abstract class Item{}
@DiscriminatorValue("ALBUM_TYPE")
public class Album extends Item{}
@DiscriminatorValue("BOOK_TYPE")
public class Book extends Item{}
@DiscriminatorValue("MOVIE_TYPE")
public class Movie extends Item{}
DB 설계를 바꿨는데도 코드를 많이 수정하지 않아도 된다!! : JPA의 큰 장점!!
Join이 성능이 안나오네 -> singletable로 고치자!! : query를 사용하면 코드를 많이 바꿔야함 근데 JPA사용하면 바꾸는게 엄청 쉽다.
1-1. 조인전략
데이터를 가져올 때 JOIN을 이용해서 가져온다.
insert는 두번 ITEAM ALBUM
select는 PK, FK를 이용해서 JOIN해서 가져온다.
abstract class에는 type을 컬럼을 두어서 구분한다.
@Inheritance(strategy = InheritanceType.JOIN)
@DiscriminatorColumn
public abstract class Item{}
1-1-1. 장점
테이블 정규화
외래 키 참조 무결성 제약조건 활용 가능
저장공간 효율화
1-1-2. 단점
조회시 조인을 많이 사용, 성능 저하
조회 쿼리가 복잡함
데이터 저장시 INSERT SQL 2번 호출
조인 성능이 생각보다 치명적이진 않고, 오히려 저장공간이 더 효율적일 수도 있음
그래도 단일 테이블 전략과 비교했을 때 단점이다!
조인이 정규화도 되고 객체랑도 잘 맞고 설계 입장에서 잘 맞아 떨어진다.
1-2. 단일 테이블 전략 - 기본 전략
subclass 의 모든 멤버변수를 테이블의 컬럼으로 가져온다.
insert도 한번에 되고, select도 한번에 되니까 아무래도 성능이 나오지!
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class Item{}
1-2-1. 장점
조인이 필요 없으므로 일반적으로 조회 성능이 빠름
조회 쿼리가 단순함
1-2-2. 단점
자식 엔티티가 매핑한 컬럼은 모두 null 허용
단일 테이블에 모든 것을 저장하므로 테이블이 커질 수 있고 상황에 따라서 조회 성능이 오히려 느려질 수 있다. NULL 조건이 데이터 무결성 입장에서 애매하다. ALBUM 저장하면 > Book, Movie 관련 column이 모두 null이 되어야한다. 조회 성능을 문제시 하려면 임계점을 넘어야하는데 보통은 없음
1-3. 구현 클래스마다 테이블 전략
subclass 자체를 테이블로 만든다 + superclass의 멤버변수도 포함해서!
superclass를 아예 없애버리고, table을 subclass 기준으로 만든 후, superclass의 멤버변수도 같이 포함하게 한다.
Item table 자체가 존재하지 않고, Movie, Book, Album table만 존재한다.
@DiscriminatorColumn의 의미가 없다! (없어도 된다.)
단순하게 값을 넣고 뺄 때는 좋은데, 이외의 경우에는 세 개 테이블을 모두 찾아봐서 쿼리가 복잡하게 나간다.
ex ) Item id가 5번이라고 할 때!
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Item{}
이 전략은 데이터베이스 설계자와 ORM 전문가 둘 다 싫어하는 전략임!
1-3-1. 장점
서브 타입을 명확하게 구분해서 처리할 때 효과적
Not Null 제약조건 사용가능
1-3-2. 단점
여러 자식 테이블을 함께 조회할 때 성능이 느림 (UNION SQL)
자식 테이블을 통합해서 쿼리하기 어려움
2. @MappedSuperclass - 매핑 정보 상속
공통 매핑 정보가 필요할 때 사용한다. (ex : baseTimeEntity 같은 것)
위에서 말한 상속 관계 매핑에서 테이블까지 고민하기 싫음. DB는 따로 쓰되, 객체입장에서 속성만 상속 받아서 쓰고 싶을때!
@MappedSuperclass
public abstract class BaseEntity {
private String createdBy;
private LocalDateTime createdDate;
private String lastModifedBy;
private LocalDateTime lastModifiedDate;
}
@Entity
public class Member extends BaseEntity{ ... }
@Entity
public class Team extends BaseEntity{ ... }
매핑 정보만 받는 슈퍼 클래스로 하고싶다면
extends 로 클래스 설정하기
@MappedSuperclass 어노테이션 추가하기.
그냥 속성을 같이 쓰고 싶을 때 사용한다!!
@Column(name = "CREATED_BY") // 이런식으로 column 설정도 충분히 가능하다.
private String createdBy;
JPA의 이벤트 기능으로 아예 어노테이션으로 시간, auth 정보를 편리하게 만들어 버릴 수 있다.
상속관계 매핑 X
엔티티X, 테이블과 매핑X (@Entity 안붙였다.)
부모 클래스를 상속 받는 자식 클래스에 매핑 정보만 제공
조회, 검색 불가(em.find(BaseEntity)불가) em.find(BaseEntity.class, 1L); 불가능
직접 생성해서 사용할 일이 없으므로 추상 클래스 권장
테이블과 관계 없고, 단순히 엔티티가 공통으로 사용하는 매핑 정보를 모으는 역할
주로 등록일, 수정일, 등록자, 수정자 같은 전체 엔티티에서 공통으로 적용하는 정보를 모을 때 사용
참고 : @Entity 클래스는 엔티티나 @MappedSuperclass로 지정한 클래스만 상속가능하다.
@MappedSuperclass //매핑 정보 상속
public abstract class BaseEntity{...}
@Entity //상속 관계 매핑
public abstract class Item extends BaseEntity{...}
@Entity
public class Album extends Item{...}
This is a summary post written after taking Kim Young-han's Java ORM Standard JPA Programming - Basics course on Inflearn.
I've been using Spring Data JPA, but Kim Young-han actually teaches JPA itself.
Based on his lectures, I'm writing this post to document concepts while testing the course source code with Spring Data JPA.
Advanced Mapping
1. Inheritance Mapping
Relational databases do NOT have inheritance
The supertype-subtype modeling technique is similar to object inheritance
Inheritance mapping: Mapping between object inheritance structure and DB supertype-subtype relationships
Ways to implement a supertype-subtype logical model into a physical model:
Convert to separate tables -> Joined strategy
Convert to a single table -> Single table strategy
Convert to subtype tables -> Table-per-class strategy
Tables can result in multiple modeling approaches, but on the object side, there's only one concept: inheritance.
The object relationships stay the same, but the DB design can vary.
Relational databases do NOT have inheritance
The supertype-subtype modeling technique is similar to object inheritance
Inheritance mapping: Mapping between object inheritance/structure and DB supertype-subtype relationships
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorColumn
@Getter
public abstract class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int price;
public Item(String name, int price) {
this.name = name;
this.price = price;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Book")
public class Book extends Item {
private String author;
private String isbn;
@Builder
public Book(String name, int price, String author, String isbn) {
super(name, price);
this.author = author;
this.isbn = isbn;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Album")
public class Album extends Item{
private String artist;
@Builder
public Album(String name, int price, String artist) {
super(name, price);
this.artist = artist;
}
}
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@DiscriminatorValue("Movie")
public class Movie extends Item {
private String actor;
private String director;
@Builder
public Movie(String name, int price, String actor, String director) {
super(name, price);
this.actor = actor;
this.director = director;
}
}
[Repository Code]
public interface ItemRepository<T extends Item> extends JpaRepository<T, Long> {}
public interface BookRepository extends JpaRepository<Book, Long> {}
public interface AlbumRepository extends JpaRepository<Album, Long> {}
public interface MovieRepository extends JpaRepository<Movie, Long> {}
Make sure to remember the ItemRepository extends part!! [How to extend JpaRepository for an abstract class]
You can retrieve Book, Album, and Movie all through ItemRepository alone. (using type casting)
[Test Code]
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ItemTest {
@Autowired
ItemRepository itemRepository;
@Autowired
EntityManager entityManager;
@Before
public void setUp() throws Exception {
Movie movie = Movie.builder()
.actor("맷데이먼")
.director("리들리스콧")
.name("마션")
.price(10000)
.build();
Book book = Book.builder()
.author("조영호")
.isbn("isbn")
.name("객체지향의 사실과 오해")
.price(10000)
.build();
Album album = Album.builder()
.artist("엔플라잉")
.name("야호")
.price(30000)
.build();
itemRepository.save(movie);
itemRepository.save(book);
itemRepository.save(album);
entityManager.clear();
}
@Test
public void Item의_서브클래스_객체들_casting으로_가져오기() {
Movie movie = (Movie) itemRepository.findAll().get(0);
Book book = (Book) itemRepository.findAll().get(1);
Album album = (Album) itemRepository.findAll().get(2);
assertThat(movie.getName()).isEqualTo("마션");
assertThat(book.getName()).isEqualTo("객체지향의 사실과 오해");
assertThat(album.getArtist()).isEqualTo("엔플라잉");
}
}
@DiscriminatorColumn(name = "DTYPE") = default: DTYPE A column called DTYPE is created in the superclass table, and the DTYPE value is set to the subclass name. In the SingleTable strategy, DTYPE may be generated even without this annotation, but you should still include it for production use.
@DiscriminatorValue("XXX") = default: classname
[Example]
@Inheritance(strategy = InheritanceType.JOIN)
@DiscriminatorColumn(name = "DTYPE")
public abstract class Item{}
@DiscriminatorValue("ALBUM_TYPE")
public class Album extends Item{}
@DiscriminatorValue("BOOK_TYPE")
public class Book extends Item{}
@DiscriminatorValue("MOVIE_TYPE")
public class Movie extends Item{}
Even when the DB design changes, you barely need to modify the code!! This is a huge advantage of JPA!!
Join performance isn't cutting it -> Let's switch to single table!! With raw queries, you'd have to change a lot of code, but with JPA it's super easy to switch.
1-1. Joined Strategy
When fetching data, it uses JOINs to retrieve it.
Insert happens twice — once for ITEM, once for ALBUM.
Select uses PK and FK to JOIN and fetch the data.
The abstract class has a type column to distinguish between subtypes.
@Inheritance(strategy = InheritanceType.JOIN)
@DiscriminatorColumn
public abstract class Item{}
1-1-1. Pros
Table normalization
Can leverage foreign key referential integrity constraints
Efficient storage space
1-1-2. Cons
Heavy use of joins during queries, potential performance degradation
Complex query statements
INSERT SQL is called twice when saving data
Join performance isn't as fatal as you might think, and it can actually be more storage-efficient.
Still, these are disadvantages compared to the single table strategy!
Joins provide normalization, align well with objects, and fit nicely from a design perspective.
1-2. Single Table Strategy - Default Strategy
All member variables of subclasses become columns in a single table.
Insert happens in one shot, select happens in one shot — so naturally the performance is better!
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
public abstract class Item{}
1-2-1. Pros
No joins needed, so query performance is generally fast
Simple query statements
1-2-2. Cons
All columns mapped by child entities must allow null
Since everything is stored in a single table, the table can get large and in some cases query performance may actually get slower. NULL conditions are awkward from a data integrity standpoint. When you save an ALBUM > all Book and Movie related columns must be null. For query performance to become a real problem, you'd need to cross a threshold, which usually doesn't happen.
1-3. Table-per-Class Strategy
Each subclass becomes its own table — including the superclass's member variables!
The superclass table is completely eliminated, tables are created based on subclasses, and they include the superclass's member variables as well.
The Item table itself doesn't exist — only Movie, Book, and Album tables exist.
@DiscriminatorColumn has no meaning here! (You don't need it.)
It's fine for simple inserts and retrieves, but for anything else, it has to search all three tables resulting in complex queries.
e.g.) When the Item id is 5!
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Item{}
This is a strategy that both database designers and ORM experts dislike!
1-3-1. Pros
Effective when you need to clearly distinguish and handle subtypes
Can use NOT NULL constraints
1-3-2. Cons
Slow performance when querying multiple child tables together (UNION SQL)
Difficult to write unified queries across child tables
2. @MappedSuperclass - Inheriting Mapping Information
Used when common mapping information is needed. (e.g., something like BaseTimeEntity)
You don't want to think about table design like in inheritance mapping above. You want the DB tables to be separate, but from the object perspective, you just want to inherit the attributes!
@MappedSuperclass
public abstract class BaseEntity {
private String createdBy;
private LocalDateTime createdDate;
private String lastModifedBy;
private LocalDateTime lastModifiedDate;
}
@Entity
public class Member extends BaseEntity{ ... }
@Entity
public class Team extends BaseEntity{ ... }
If you want a superclass that only provides mapping information:
Set up the class with extends
Add the @MappedSuperclass annotation.
Use it when you simply want to share attributes!!
@Column(name = "CREATED_BY") // 이런식으로 column 설정도 충분히 가능하다.
private String createdBy;
With JPA's event features, you can conveniently create time and auth information using annotations alone.
NOT inheritance mapping
NOT an entity, NOT mapped to a table (@Entity is not applied.)
Only provides mapping information to child classes that inherit from the parent class
Cannot be queried or searched (em.find(BaseEntity) is not possible) em.find(BaseEntity.class, 1L); is not possible
Since you'll never instantiate it directly, abstract class is recommended
Has no relation to tables — it simply gathers mapping information commonly used by entities
Mainly used to collect information like created date, modified date, created by, modified by that applies commonly across all entities
Note: @Entity classes can only extend entities or classes annotated with @MappedSuperclass.
@MappedSuperclass //매핑 정보 상속
public abstract class BaseEntity{...}
@Entity //상속 관계 매핑
public abstract class Item extends BaseEntity{...}
@Entity
public class Album extends Item{...}
select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_,
team1_.member_id as member_i1_1_1_,
team1_.name as name2_1_1_
from
member member0_
left outer join
team team1_
on member0_.team_id=team1_.member_id
where member0_.member_id=?
자동적으로 Member를 조회하는데 Team도 join이 되서 같이 조회가된다.
@Test
public void 멤버만_조회() {
Member findMember = entityManager.getReference(Member.class, 1L);
}
before findMember = class com.jyami.jpalab.domain.Member$HibernateProxy$EYDMo7wU
Hibernate: [select query]
findMember.username = member1
after findMember = class com.jyami.jpalab.domain.Member$HibernateProxy$EYDMo7wU
프록시 객체는 원본 엔티티를 상속 받음, 따라서 타입 체크시 주의해야함 (== 비교 실패, instance of 사용) => 프록시로 넘어올지, 원래 객체 타입으로 넘어올지 모른다
프록시 클래스 확인 방법 entity.getClass().getName() 출력 (..javasist.. or HibernateProxy..)
System.out.println("refMember = " + refMember.getClass()); //클래스 확인
System.out.println(refMember.getUsername()); //강제 호출
프록시 강제 초기화
System.out.println("refMember = " + refMember.getClass());
Hibernate.initialize(refMember); // 강제 초기화
참고: JPA 표준은 강제 초기화 없음 강제 호출: member.getName()
2. 즉시로딩과 지연로딩
2-1. 지연로딩 LAZY를 사용해서 프록시로 조회
멤버 클래스만 DB에서 조회한다.
@ManyToOne(fetch = FetchType.LAZY) ///fecth 설정을 해준다.
@JoinColumn(name = "TEAM_ID")
private Team team;
@Test
public void 지연로딩() {
Member member = memberRepository.findById(1L).get();
assertThat(member.getUsername()).isEqualTo("MemberDefault");
System.out.println("m = " + member.getTeam().getClass());
//getTeam()은 프록시 가져오는 것
}
Hibernate: select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_
from
member member0_
where
member0_.member_id=?
m = class com.jyami.jpalab.domain.Team$HibernateProxy$gs0vf0Qv
select
team0_.member_id as member_i1_1_0_,
team0_.name as name2_1_0_
from
team team0_
where
team0_.member_id=?
그래서 위와 같이 영속성 컨텍스트 초기화를 하게 될 때 그때 쿼리가 나간다.
Member에서 Team을 가져올 때 Lazy로 설정해두었기 때문에, Team 객체 안에는 프록시 객체를 넣어둔다. 실제 team을 사용하는 시점에 영속성 컨텍스트 초기화를 한다.
BM 상에서 Member조회시 Team을 같이 조회하지 않을 때 LAZY를 사용하면!
2-2. 즉시로딩 EAGER를 사용해서 함께 조회
@ManyToOne(fetch = FetchType.EAGER) ///fecth 설정을 해준다.
@JoinColumn(name = "TEAM_ID")
private Team team;
Hibernate: insert into team (member_id, name) values (null, ?)
Hibernate: insert into member (member_id, team_id, username) values (null, ?, ?)
Hibernate: select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_,
team1_.member_id as member_i1_1_1_,
team1_.name as name2_1_1_
from
member member0_
left outer join
team team1_ on member0_.team_id=team1_.member_id
where
member0_.member_id=?
m = class com.jyami.jpalab.domain.Team
즉시 로딩이기 때문에 Proxy를 가져올 필요가 없어서 getClass() 를 했을 때 실제 객체가 나온다!
proxy를 가져오지 않으니까 영속성 컨텍스트 초기화를 해줄 필요가 없다.
BM 상에서 Mebmer를 쓸때 항상 Team도 조회할 경우!
JPA 구현체는 가능하면 조인을 사용해서 SQL 한번에 함께 조회
2-3. 프록시와 즉시로딩 주의
가급적 지연 로딩만 사용(특히 실무에서) 만약 관련 링크객체가 N개면 N개만큼 Join이 발생해서 나간다.
즉시 로딩을 적용하면 예상하지 못한 SQL이 발생
즉시로딩을 JPQL에서 N+1 문제를 일으킨다.
@ManyToOne, @OneToOne은 기본이 즉시로딩 -> LAZY로 설정 (X To One 시리즈)
@OneToMany, @ManyToMany는 기본이 지연 로딩
2-3-1. JPQL N+1 문제 preview
@Test
public void JPQL의_N_플러스_1_문제() {
List<Member> members = entityManager.createQuery("select m from Member m", Member.class)
.getResultList();
}
Hibernate: select
member0_.member_id as member_i1_0_,
member0_.team_id as team_id3_0_,
member0_.username as username2_0_
from
member member0_
Hibernate: select
team0_.member_id as member_i1_1_0_,
team0_.name as name2_1_0_
from
team team0_
where
team0_.member_id=?
쿼리가 두번나간다!!
JPQL : 1번째 파라미터가 sql query로 그대로 읽힌다. 따라서 쿼리대로 Member를 가져온다. 근데 Team이 즉시로딩이 되어있음! 즉시로딩이라 무조껀 그안에 값이 들어가 있어야 하기 때문에 Team도 가져온다. 따라서 Team 쿼리를 또 따로 보낸다.
쿼리가 N+1 나간다
1 : 처음에 내보낸 쿼리 (N개의 Member 리턴)
N : EAGER 설정이 되어있어 참조 객체를 가져오기 위한 추가 쿼리 (N개의 Member 각각의 Team 값을 채우기 위해 각 Team을 찾기위해 N개의 쿼리가 나간다.)
Hibernate: insert into parent (id, name) values (null, ?)
Hibernate: insert into child (id, name, parent_id) values (null, ?, ?)
Hibernate: insert into child (id, name, parent_id) values (null, ?, ?)
---
Hibernate: select parent0_.id as id1_2_0_, parent0_.name as name2_2_0_ from parent parent0_ where parent0_.id=?
Hibernate: select childlist0_.parent_id as parent_i3_0_0_, childlist0_.id as id1_0_0_, childlist0_.id as id1_0_1_, childlist0_.name as name2_0_1_, childlist0_.parent_id as parent_i3_0_1_ from child childlist0_ where childlist0_.parent_id=?
심플하게 Parent를 저장할 때, Parent안에 있는 객체인 Child도 같이 저장할 때
3-1. CASCADE의 종류
ALL : 모두 적용
PERSIST : 영속 - 저장할 때만 lifecycle을 맞출래
REMOVE : 삭제
MERGE : 병합
REFERESH : refresh
DETACH : detach
하나의 부모가 자식들을 관리할 때는 의미가 있다. ex ) 게시판에 댓글, 첨부파일의 경로 등이 들어갈 때 : 의미 있음
그러나 여러 엔티티에서 관리한다면 쓰면 안된다.
소유자가 하나일 때는 써도 된다.
단일 엔티티에 완전히 종속적일 때 사용하자
Child와 Parent의 lifecycle이 완전히 비슷할 때 사용하자
4. 고아객체
고아 객체 제거 : 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제 JPA는 부모 엔티티와 연관관계가 끊어진 자식 엔티티를 자동으로 삭제하는 기능을 제공하는데 이것을 고아 객체 제거라 한다. 이 기능을 사용해서 부모 엔티티의 컬렉션에서 자식 엔티티의 참조만 제거하면 자식 엔티티가 자동으로 삭제 된다.
select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_,
team1_.member_id as member_i1_1_1_,
team1_.name as name2_1_1_
from
member member0_
left outer join
team team1_
on member0_.team_id=team1_.member_id
where member0_.member_id=?
When querying Member, Team is automatically joined and fetched together.
@Test
public void 멤버만_조회() {
Member findMember = entityManager.getReference(Member.class, 1L);
}
findMember = class com.jyami.jpalab.domain.Member$HibernateProxy$injSwDL2
The name isn't Member! HibernateProxy: it's a forcibly created fake class — a proxy class
1-2. Proxy Characteristics
Created by inheriting the actual class
Looks the same as the actual class on the outside
From the user's perspective, you don't need to distinguish between the real object and the proxy object (in theory)
The proxy object holds a reference (target) to the actual object
When you call the proxy object, it delegates the call to the actual object's method
em.getReference(Member.class, 1L); //프록시객체 가져온다.
getName() > The Member target has no value > Requests the persistence context to fetch the actual value > The DB fetches that value and links the real object to the Proxy object. So it gets the name via target.getName().
Initialization request to the persistence context: when the proxy has no value, ask the DB for the real value.
1-3. Proxy Object Mechanism
The proxy object is initialized only once, on first use
@Test
public void 프록시_테스트() {
Member findMember = entityManager.getReference(Member.class, 1L);
System.out.println("1st = " + findMember.getUsername());
//1st에서는 query가 나간다.
System.out.println("2nd = " + findMember.getUsername());
//2nd에서는 query가 나가지 않는다.
}
When a proxy object is initialized, it doesn't turn into the actual entity — once initialized, you can access the actual entity through the proxy object
before findMember = class com.jyami.jpalab.domain.Member$HibernateProxy$EYDMo7wU
Hibernate: [select query]
findMember.username = member1
after findMember = class com.jyami.jpalab.domain.Member$HibernateProxy$EYDMo7wU
The proxy object inherits the original entity, so be careful with type checking (== comparison fails, use instanceof) => You never know if it'll come as a proxy or the original object type
How to check the proxy class: print entity.getClass().getName() (..javasist.. or HibernateProxy..)
System.out.println("refMember = " + refMember.getClass()); //클래스 확인
System.out.println(refMember.getUsername()); //강제 호출
Force initialize a proxy
System.out.println("refMember = " + refMember.getClass());
Hibernate.initialize(refMember); // 강제 초기화
Note: The JPA standard does not have forced initialization Forced invocation: member.getName()
2. Eager Loading and Lazy Loading
2-1. Using Lazy Loading (LAZY) to Fetch via Proxy
Only the Member class is fetched from the DB.
@ManyToOne(fetch = FetchType.LAZY) ///fecth 설정을 해준다.
@JoinColumn(name = "TEAM_ID")
private Team team;
@Test
public void 지연로딩() {
Member member = memberRepository.findById(1L).get();
assertThat(member.getUsername()).isEqualTo("MemberDefault");
System.out.println("m = " + member.getTeam().getClass());
//getTeam()은 프록시 가져오는 것
}
Hibernate: select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_
from
member member0_
where
member0_.member_id=?
m = class com.jyami.jpalab.domain.Team$HibernateProxy$gs0vf0Qv
You can see that only Member is queried! And Team returns a proxy object.
select
team0_.member_id as member_i1_1_0_,
team0_.name as name2_1_0_
from
team team0_
where
team0_.member_id=?
So the query is only fired when the persistence context initialization happens, like above.
Since fetching Team from Member is set to Lazy, a proxy object is placed inside the Team object. The persistence context initialization happens at the point when Team is actually used.
When you don't need to fetch Team together when querying Member in your business model, use LAZY!
2-2. Using Eager Loading (EAGER) to Fetch Together
@ManyToOne(fetch = FetchType.EAGER) ///fecth 설정을 해준다.
@JoinColumn(name = "TEAM_ID")
private Team team;
Hibernate: insert into team (member_id, name) values (null, ?)
Hibernate: insert into member (member_id, team_id, username) values (null, ?, ?)
Hibernate: select
member0_.member_id as member_i1_0_0_,
member0_.team_id as team_id3_0_0_,
member0_.username as username2_0_0_,
team1_.member_id as member_i1_1_1_,
team1_.name as name2_1_1_
from
member member0_
left outer join
team team1_ on member0_.team_id=team1_.member_id
where
member0_.member_id=?
m = class com.jyami.jpalab.domain.Team
Since it's eager loading, there's no need to fetch a Proxy, so when you call getClass(), the actual object is returned!
Since it doesn't fetch a proxy, there's no need for persistence context initialization.
Use this when you always need to fetch Team whenever you use Member in your business model!
The JPA implementation tries to use joins to fetch everything in a single SQL query
2-3. Cautions with Proxy and Eager Loading
Use lazy loading as much as possible (especially in production) If there are N related linked objects, N joins will be executed.
Applying eager loading can cause unexpected SQL queries
Eager loading causes the N+1 problem in JPQL
@ManyToOne and @OneToOne default to eager loading -> Set them to LAZY (the X-To-One series)
@OneToMany and @ManyToMany default to lazy loading
2-3-1. JPQL N+1 Problem Preview
@Test
public void JPQL의_N_플러스_1_문제() {
List<Member> members = entityManager.createQuery("select m from Member m", Member.class)
.getResultList();
}
Hibernate: select
member0_.member_id as member_i1_0_,
member0_.team_id as team_id3_0_,
member0_.username as username2_0_
from
member member0_
Hibernate: select
team0_.member_id as member_i1_1_0_,
team0_.name as name2_1_0_
from
team team0_
where
team0_.member_id=?
Two queries are fired!!
JPQL: The first parameter is read directly as an SQL query. So it fetches Member as the query specifies. But Team is set to eager loading! Since it's eager, the values must always be populated, so it fetches Team too. Therefore, it sends a separate query for Team.
N+1 queries are fired
1: The initial query (returns N Members)
N: Additional queries to fetch referenced objects due to EAGER setting (N queries are fired to fill in each Team value for each of the N Members)
If you set this to LAZY, it just fetches Member, and since Team is a proxy object, only 1 query is fired.
The basic solution is fetch join: it dynamically selects and fetches only what you want at runtime. Since within the application there are times when you only need Member vs. times when you need Member + Team:
List<Member> members = entityManager.createQuery("select m from Member m join fecth m.team", Member.class).getResultList();
Everything is included in this single query.
2-4. Lazy Loading in Practice
This is all very theoretical for now — in practice, you should just use LAZY for everything.
Member and Team are frequently used together: Eager loading
Member and Order are occasionally used together: Lazy loading
Order and Product are frequently used together: Eager loading
3. Cascade (Persistence Propagation)
When making a specific entity persistent, you may want to make its associated entities persistent as well
Example: Saving child entities together when saving a parent entity
Cascade has nothing to do with mapping relationships
It simply provides the convenience of persisting associated entities together when persisting an entity
@Entity
@NoArgsConstructor
@Getter
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
//cascade 옵션 : Parent를 저장할 때 child도 같이 저장하고 싶다.
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> childList = new ArrayList<>();
@Builder
public Parent(String name) {
this.name = name;
}
}
@Entity
@Getter
@NoArgsConstructor
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn
private Parent parent;
@Builder
public Child(String name, Parent parent) {
this.name = name;
this.parent = parent;
parent.getChildList().add(this); //양방향 위해 추가함!
}
}
Hibernate: insert into parent (id, name) values (null, ?)
Hibernate: insert into child (id, name, parent_id) values (null, ?, ?)
Hibernate: insert into child (id, name, parent_id) values (null, ?, ?)
---
Hibernate: select parent0_.id as id1_2_0_, parent0_.name as name2_2_0_ from parent parent0_ where parent0_.id=?
Hibernate: select childlist0_.parent_id as parent_i3_0_0_, childlist0_.id as id1_0_0_, childlist0_.id as id1_0_1_, childlist0_.name as name2_0_1_, childlist0_.parent_id as parent_i3_0_1_ from child childlist0_ where childlist0_.parent_id=?
Simply put, when saving a Parent, you also want to save the Child objects inside the Parent.
3-1. Types of CASCADE
ALL: Apply all
PERSIST: Persistence — only sync the lifecycle when saving
REMOVE: Delete
MERGE: Merge
REFERESH: Refresh
DETACH: Detach
It's meaningful when a single parent manages its children. e.g.) When a board post has comments, attachment file paths, etc.: meaningful
However, you should NOT use it when multiple entities manage the same thing.
It's fine to use when there's a single owner.
Use it when something is completely dependent on a single entity.
Use it when the lifecycles of Child and Parent are completely aligned.
4. Orphan Objects
Orphan removal: Automatically deletes child entities whose relationship with the parent entity is severed. JPA provides a feature that automatically deletes child entities that are disconnected from their parent entity — this is called orphan removal. Using this feature, if you simply remove the reference to a child entity from the parent entity's collection, the child entity is automatically deleted.
The relationship is severed > a DELETE is executed.
public class Parent{
@OneToMany(mappedBy = "parent", orphanRemoval = true) // orphanRemoval 옵션 추가
private List<Child> childList = new ArrayList<>();
}
It treats entities whose references have been removed as orphan objects that are not referenced anywhere else, and deletes them
Should only be used when there is exactly one place referencing it!!
Use when a specific entity has sole ownership
Only available for @OneToOne and @OneToMany
Note: Conceptually, when a parent is removed, the children become orphans. Therefore, when orphan removal is enabled, removing the parent also removes the children. This behaves like CascadeType.REMOVE.
Hmm, but why isn't it working for me 😭 I should ask about this.
5. Cascade + Orphan Removal, Lifecycle
public class Parent{
@OneToMany(mappedBy = "parent", cascade = CascadeType=ALL, orphanRemoval = true)
private List<Child> childList = new ArrayList<>();
}
CascadeType.ALL + orphanRemoval = true
Entities that manage their own lifecycle use em.persist() to persist and em.remove() to remove
When both options are enabled, you can manage the child's lifecycle through the parent entity. The child repository becomes unnecessary.
Useful when implementing the Aggregate Root concept from Domain-Driven Design (DDD)
I've been using Spring Data JPA, but Kim Young-han actually teaches JPA itself.
Based on his lectures, I decided to write this post to test the course material with Spring Data JPA and document the concepts.
Various Association Mappings
1. Three Things to Consider When Mapping Associations
1-1. Multiplicity
Many-to-One [N:1] : @ManyToOne
One-to-Many [1:N] : @OneToMany
One-to-One [1:1] : @OneToOne
Many-to-Many [N:M] : @ManyToMany
1-2. Unidirectional vs. Bidirectional
1-3. Owner of the Association
Tables establish an association between two tables with a single foreign key
In a bidirectional object relationship, there are two references: A→B and B→A
Since there are two references in a bidirectional object relationship, you need to designate which side manages the foreign key When you change A, should B also change? / When you change B, should A also change?
Owner of the association: the reference that manages the foreign key
Inverse side: does not affect the foreign key
2. Many-to-One [N:1]
Owner of the association: N side
2-1. Many-to-One Unidirectional
Member : N - Team : 1
Member references Team.
@Entity
@Getter
@Setter
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@ManyToOne
@JoinColumn(name = "TEAM_ID") // 외래키
private Team team;
}
@Entity
@Getter
@Setter
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
private String name;
}
You place the reference and map the association where the foreign key exists.
From the DB's perspective, the FK naturally belongs on the N side.
If it were on the Team side instead, you'd need a list, and the design wouldn't make sense.
This is the most commonly used mapping
The inverse of Many-to-One is One-to-Many
2-2. Many-to-One Bidirectional
Member : N - Team : 1
Member references Team. And Team also references Member!
The owner of the association manages the FK. Since the inverse side can only read anyway, you just need to add a List to Team.
Here, it's important to specify with mappedBy that this side reads from the association owner
// Team 클래스
@OneToMany(mappedBy = "team") //참조를 당하는 쪽에서 읽기만 가능!
private List<Member> members = new ArrayList<>();
The side with the foreign key is the owner of the association
Develop so that both sides reference each other
3. One-to-Many [1:N]
3-1. One-to-Many Unidirectional
This is not recommended.
Centered around Team: Team manages the foreign key
Team wants to know about Member, but Member doesn't want to know about Team.
From the DB's perspective: the FK must be on the Member table.
When you modify Team's List, you have to update the TEAM_ID of some row in the Member table in the DB.
@Entity
@Getter
@Setter
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
}
@Entity
@Getter
@Setter
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
private String name;
@OneToMany
@JoinColumn(name = "TEAM_ID")
private List<Member> members = new ArrayList<>();
}
The data goes into the DB fine, but extra queries like UPDATE queries are fired.
When saving the Member list from Team, the team_id in the Member table also needs to be updated.
You touched Team, but it affects the Member table — this makes it a bit harder to understand and trace.
In One-to-Many unidirectional, the One (1) side is the owner of the association
In a One-to-Many table relationship, the foreign key is always on the Many (N) side
Due to the mismatch between objects and tables, this results in an unusual structure where you manage the foreign key of the opposite table
You must use @JoinColumn. Otherwise, it uses a join table strategy (adds an intermediate table) — a middle table like team_member gets created with team_id and member_id. The downside: having one extra table makes operations harder.
Downsides of One-to-Many unidirectional mapping
The foreign key managed by the entity is in a different table
Additional UPDATE SQL is executed to manage the association
Use Many-to-One bidirectional mapping instead of One-to-Many unidirectional — sacrifice a bit on the object relationship side!
3-2. One-to-Many Bidirectional
This kinda works as a hacky workaround lol
// Member 클래스
@ManyToOne
@JoinColumn(name="TEAM_ID", insertable = false, updatable = false) //중요!!
private Team team;
But this way, both Team and Member have @JoinColumn, making both of them owners of the association.
So you use JoinColumn options — the mapping exists and values are all there, but you block insertable and updatable to make it read-only.
Management is done through Team, and Member only reads.
This mapping doesn't officially exist
@JoinColumn(insertable=false, updatable=false)
A way to use it like bidirectional by using a read-only field
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class MemberTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Before
public void setUp() throws Exception {
Team team = Team.builder()
.name("TeamA")
.build();
// teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
memberRepository.save(member);
}
@Test
public void 잘_저장되었는지_불러오기() {
Member member = memberRepository.findAll().get(0);
String username = member.getUsername();
assertThat(username).isEqualTo("member1");
Team team = member.getTeam();
assertThat(team.getName()).isEqualTo("TeamA");
List<Member> members = team.getMembers();
for (Member m : members) {
assertThat(m.getUsername()).startsWith("member");
}
}
강좌랑 cascade 부분만 달라서 왜 그런가 하고 생각해 봤는데 강좌에서는 save를 두번 했었다. 강좌코드 대로 코딩하고 테스트한 결과는 아래
@Entity
@Getter
@NoArgsConstructor
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
// @ManyToOne(cascade = CascadeType.ALL)
@ManyToOne
@JoinColumn(name = "TEAM_ID")
private Team team;
@Builder
private Member(String username, Team team) {
this.username = username;
this.team = team;
}
}
@Entity
@Getter
@NoArgsConstructor
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
private String name;
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
@Builder
private Team(String name) { //여기 그냥 members도 param으로 넣었다가 에러 팡!
this.name = name;
}
}
테스트코드
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class MemberTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Before
public void setUp() throws Exception {
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
memberRepository.save(member);
}
@Test
public void 잘_저장되었는지_불러오기() {
Member member = memberRepository.findAll().get(0);
String username = member.getUsername();
assertThat(username).isEqualTo("member1");
Team team = member.getTeam();
assertThat(team.getName()).isEqualTo("TeamA");
List<Member> members = team.getMembers();
for (Member m : members) {
assertThat(m.getUsername()).startsWith("member");
}
}
}
Member 저장할 때 Team을 저장하도록 cascade 설정을 하지 않고,
TestCode 작성시에 Member save , Team save를 각각 해줬다
Team이 이미 save가 된 상태에서 Member를 save할 경우인데,
어차피 DB에서는 Member에 FK가 있기 때문에 매핑이 가능해진다!
객체에서의 매핑은 이미 Team, Member 모두 각자의 참조객체를 갖고있기 때문에 가능하고!
내가 처음에 작성한 코드의 경우에는 member만 저장해서 team도 같이 저장하는 것이었기 때문에 Member를 저장할 때 cascade 옵션을 줘야했다.
따라서 Member repository에 저장하더라도, Team의 Insert를 먼저 실행 후에, Member insert를 진행하여 Member Table의 FK에 Team을 저장해준다.
Hibernate: insert into team (member_id, name) values (null, ?)
Hibernate: insert into member (member_id, team_id, username) values (null, ?, ?)
Hibernate: select member0_.member_id as member_i1_0_, member0_.team_id as team_id3_0_, member0_.username as username2_0_ from member member0_
Q. 양방향 매핑이 좋은가?
A. 객체는 사실 단방향이 좋다! -> 신경쓸게 많음
2-3. 객체와 테이블이 관계를 맺는 차이
2-3-1. 객체의 연관관계 - 2개
Member -> Team 연관관계 1개 (단방향) - Team 레퍼런스 객체
Team -> Member 연관관계 1개 (단방향) - Member 레퍼런스 객체
객체의 양방향 관계는 사실 양방향 관계가 아니라 서로 다른 단방향 관계 2개다
객체를 양방향으로 참조하려면 단방향 연관 관계를 2개 만들어야 한다.
class Member{
Team team; // TEAM -> Member (team.getMember())
}
class Team{
Member member; // MEMBER -> TEAM (member.getTeam())
}
2-3-2. 테이블의 연관관계 - 1개
Team <-> Member 연관관계 1개 (양방향) - FK하나로 양쪽의 연관관계 알 수 있음 (join)
테이블은 외래 키 하나로 두 테이블의 연관관계를 관리
MEMBER.TEAM_ID 외래 키 하나로 양방향 연관관계 가짐 (양쪽으로 조인할 수 있다.)
SELECT *
FROM MEMBER M
JOIN TEAM T ON M.TEAM_ID = T.TEAM_ID
SELECT *
FROM TEAM T
JOIN MEMBER M ON T.TEAM_ID = M.TEAM_ID
2-4. 연관관계의 주인
딜레마가 생긴다 > solution : 둘중 하나로 외래키를 관리한다!
Team에 있는 List 로 FK를 관리할지
Member에 있는 Team으로 FK를 관리할지
2-4-1. 양방향 매핑 규칙
객체의 두 관계중 하나를 연관관계의 주인으로 지정
연관관계의 주인만이 외래 키를 관리 (등록, 수정)
주인이 아닌쪽은 읽기만 가능
주인은 mappedBy 속성 사용X
주인이 아니면 mappedBy 속성으로 주인 지정
mappedBy : 나는 누군가에 의해서 매핑이 되었어! 나는 주인이 아니야!
public class Team {
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
}
public class Member {
@ManyToOne
@JoinColumn(name = "TEAM_ID")
private Team team;
}
mappedBy : 나는 team에 의해서 관리가 된다 : Member 객체의 team 변수에 의해서 관리된다.
@JoinColumn의 Team: 나는 앞으로 Team을 관리할꺼야
2-4-2. 누구를 주인으로?
외래키가 있는 곳을 주인으로 정해라
여기서는 Member.team이 연관관계의 주인!
성능 이슈!
Member의 경우에는 insert 쿼리 하나인데
Team의 경우에는 insert 쿼리 + update 쿼리
DB 입장에서 외래키가 있는 곳이 무조건 N
= N 이 있는 곳이 무조건 주인
= @ManyToOne 이 무조건 주인
3. 양방향 연관관계와 연관관계의 주인 : 주의점, 정리
3-1. 양방향 매핑시 가장 많이 하는 실수
연관관계의 주인에 값을 입력하지 않음
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class FailTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Autowired
EntityManager entityManager;
@Test
public void 일차캐싱에_따른_저장_테스트() {
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
// team.getMembers().add(member);
memberRepository.save(member);
// 주인(Member)이 연관관계를 설정하지 않음!!
// 역방향(주인이 아닌 방향)만 연관관계 설정
// entityManager.clear();
Team findTeam = teamRepository.findAll().get(0);
List<Member> members = findTeam.getMembers();
assertThat(members).isEmpty();
}
}
entityManager.clear(); 을 안했을 경우 : 1차 캐시를 해서 영속성 컨텍스트가 되어있는 상태 값 세팅 연관관계가 되어있는걸 그냥 가져온다. 이렇게 실행하면 DB에서 select 쿼리가 안 나간다.
Team이 그냥 영속성 컨텍스트에 들어가있어서, team에는 현재 member가 없는상태. 그러다보니 1차 캐싱으로 인해 아무것도 안들어가 있음!
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
team.getMembers().add(member);
이런식으로 Member에 한줄을 넣어주기 보다! 연관관계 편의 메소드를 생성하자
Member에서 team을 set 해줄때 설정해버린다. - 하나면 세팅해도 두개가 같이 세팅이 되게!
I've been using Spring Data JPA, but Kim Young-han actually teaches JPA itself.
Based on his lectures, I decided to write this post to test the course material using Spring Data JPA and document the concepts.
Association Mapping Basics
1. Unidirectional Association
<Haven't watched this part yet>
2. Bidirectional Association and the Owner of the Relationship: Basics
Bidirectional association -> references go both ways.
Object: uses references Table: uses FK joins
We need to look at the paradigm difference between objects and tables.
2-1. Table Associations
There's no difference between unidirectional and bidirectional.
Whether you want to know TEAM->MEMBER or MEMBER->TEAM, you can find out by joining with the Foreign Key. Regardless of whether it's bidirectional or unidirectional, you can figure out all associations with just the FK.
2-2. Object Associations
If Member has a Team variable, it can navigate to Team. Team needs to have a List to navigate to Member.
Objects need to hold references to each other as member variables to be able to access one another.
[Note]: When using a List member variable, always initialize it with new ArrayList<>()! This prevents NullPointerError when calling add()!
@Entity
@Getter
@NoArgsConstructor
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
private String name;
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
@Builder
private Team(String name) { //여기 그냥 members도 param으로 넣었다가 에러 팡!
this.name = name;
}
}
@Entity
@Getter
@NoArgsConstructor
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name= "TEAM_ID")
private Team team;
@Builder
private Member(String username, Team team) {
this.username = username;
this.team = team;
}
}
Now graph traversal is possible in the reverse direction as well.
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class MemberTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Before
public void setUp() throws Exception {
Team team = Team.builder()
.name("TeamA")
.build();
// teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
memberRepository.save(member);
}
@Test
public void 잘_저장되었는지_불러오기() {
Member member = memberRepository.findAll().get(0);
String username = member.getUsername();
assertThat(username).isEqualTo("member1");
Team team = member.getTeam();
assertThat(team.getName()).isEqualTo("TeamA");
List<Member> members = team.getMembers();
for (Member m : members) {
assertThat(m.getUsername()).startsWith("member");
}
}
The only difference from the course was the cascade part, and when I thought about why, it's because the course called save twice. Here's the test result after coding it exactly like the course:
@Entity
@Getter
@NoArgsConstructor
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
// @ManyToOne(cascade = CascadeType.ALL)
@ManyToOne
@JoinColumn(name = "TEAM_ID")
private Team team;
@Builder
private Member(String username, Team team) {
this.username = username;
this.team = team;
}
}
@Entity
@Getter
@NoArgsConstructor
public class Team {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "MEMBER_ID")
private Long id;
private String name;
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
@Builder
private Team(String name) { //여기 그냥 members도 param으로 넣었다가 에러 팡!
this.name = name;
}
}
Test code
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class MemberTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Before
public void setUp() throws Exception {
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
memberRepository.save(member);
}
@Test
public void 잘_저장되었는지_불러오기() {
Member member = memberRepository.findAll().get(0);
String username = member.getUsername();
assertThat(username).isEqualTo("member1");
Team team = member.getTeam();
assertThat(team.getName()).isEqualTo("TeamA");
List<Member> members = team.getMembers();
for (Member m : members) {
assertThat(m.getUsername()).startsWith("member");
}
}
}
Without setting cascade on Member to also save Team,
I called save separately for both Member and Team in the test code.
Since Team is already saved before saving Member,
the mapping works because the FK exists in the Member table in the DB!
On the object side, the mapping works because both Team and Member already hold their own reference objects!
In my original code, I was saving only member and having team saved along with it, so I needed the cascade option on Member.
Therefore, even though we're saving through the Member repository, it executes the Team's INSERT first, then proceeds with the Member INSERT, storing the Team in the Member table's FK.
Hibernate: insert into team (member_id, name) values (null, ?)
Hibernate: insert into member (member_id, team_id, username) values (null, ?, ?)
Hibernate: select member0_.member_id as member_i1_0_, member0_.team_id as team_id3_0_, member0_.username as username2_0_ from member member0_
Q. Is bidirectional mapping better?
A. Actually, unidirectional is better for objects! -> There's a lot more to worry about
2-3. Differences in How Objects and Tables Form Relationships
2-3-1. Object Associations - 2
Member -> Team: 1 association (unidirectional) - Team reference object
Team -> Member: 1 association (unidirectional) - Member reference object
A bidirectional relationship in objects is not truly bidirectional — it's actually two separate unidirectional relationships
To reference objects bidirectionally, you need to create two unidirectional associations.
class Member{
Team team; // TEAM -> Member (team.getMember())
}
class Team{
Member member; // MEMBER -> TEAM (member.getTeam())
}
2-3-2. Table Associations - 1
Team <-> Member: 1 association (bidirectional) - A single FK lets you know both sides of the relationship (join)
Tables manage the association between two tables with a single foreign key
The MEMBER.TEAM_ID foreign key alone provides a bidirectional association (you can join from either side.)
SELECT *
FROM MEMBER M
JOIN TEAM T ON M.TEAM_ID = T.TEAM_ID
SELECT *
FROM TEAM T
JOIN MEMBER M ON T.TEAM_ID = M.TEAM_ID
2-4. The Owner of the Relationship
A dilemma arises > solution: manage the foreign key from one side!
Should we manage the FK through the List in Team?
Or through the Team in Member?
2-4-1. Bidirectional Mapping Rules
Designate one of the two object relationships as the owner of the relationship
Only the owner of the relationship can manage the foreign key (create, update)
The non-owner side can only read
The owner does NOT use the mappedBy attribute
The non-owner uses mappedBy to specify the owner
mappedBy: "I'm mapped by someone else! I'm not the owner!"
public class Team {
@OneToMany(mappedBy = "team")
private List<Member> members = new ArrayList<>();
}
public class Member {
@ManyToOne
@JoinColumn(name = "TEAM_ID")
private Team team;
}
mappedBy: "I'm managed by team" — meaning it's managed by the team variable in the Member object.
@JoinColumn's Team: "I'm going to manage Team from now on"
2-4-2. Who Should Be the Owner?
Make the side where the foreign key exists the owner
In this case, Member.team is the owner of the relationship!
Performance issue!
For Member, it's just one INSERT query,
but for Team, it's an INSERT query + an UPDATE query
From the DB's perspective, the side with the foreign key is always the N (many) side
= The N side is always the owner
= @ManyToOne is always the owner
3. Bidirectional Association and the Owner of the Relationship: Pitfalls and Summary
3-1. The Most Common Mistake in Bidirectional Mapping
Not setting a value on the owner of the relationship
@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class FailTest {
@Autowired
MemberRepository memberRepository;
@Autowired
TeamRepository teamRepository;
@Autowired
EntityManager entityManager;
@Test
public void 일차캐싱에_따른_저장_테스트() {
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
// team.getMembers().add(member);
memberRepository.save(member);
// 주인(Member)이 연관관계를 설정하지 않음!!
// 역방향(주인이 아닌 방향)만 연관관계 설정
// entityManager.clear();
Team findTeam = teamRepository.findAll().get(0);
List<Member> members = findTeam.getMembers();
assertThat(members).isEmpty();
}
}
When entityManager.clear() is not called: Since first-level caching is active and the persistence context still holds the values, it just fetches the existing association state. When executed this way, no SELECT query is actually sent to the DB.
Team is just sitting in the persistence context, and at this point, it has no members. Because of first-level caching, nothing is populated!
From an object-oriented perspective, you should set values on both sides!
3-2. Bidirectional Association Precautions
Always set values on both sides, considering the pure object state
Create convenience methods for managing associations
Watch out for infinite loops in bidirectional mapping e.g.) toString(), Lombok, JSON serialization libraries
Team team = Team.builder()
.name("TeamA")
.build();
teamRepository.save(team);
Member member = Member.builder()
.username("member1")
.team(team)
.build();
team.getMembers().add(member);
Rather than adding a separate line for Member like this, create a convenience method for the association!
Set it up when setting the team on Member — so that setting one side automatically sets both!
Spring platform에 대한 기본 설정 뿐만아니라 다른 library에 대한 설정(tomcat)도 기본적으로 해준다
목표
모든 스프링 개발을 할 때 더 빠르고 더 폭넓은 사용성을 제공한다.
일일히 설정하지 않아도 convention으로 정해져있는 설정을 제공한다. 하지만 우리의 요구사항에 맞게 이런 설정을 쉽고 빠르게 바꿀 수 있다.(스프링 부트를 사용하는 이유)
non-fucntional 설정도 제공해 준다. 비즈니스로직 구현에 필요한 기능 외에도 non-functional feature도!
XML 사용하지 않고, code generation도 하지 않는다.
Spring 루 : 독특하게 code generation을 해주는데 지금은 잘 사용되지 않는다. generation을 안해서 더 쉽고 명확하고 커스터마이징하기 쉽다. > spring boot의 bb
System Requirements
Spring boot 는 java 8 이상을 필요로 한다.
지원하는 servletContainer로는 tomcat, jetty Undertow가 있다.
2. Spring Boot 시작하기
Intellij ultimate를 사용하면 Spring boot initializer가 있으나, community 버전은 없다. 따라서 자신이 원하는 build tool을 이용해서 만들어 주면된다 Spring boot initializer를 이용하지 않고, 프로젝트 생성하는 법 을 공부 할 것이다.
2-1. gradle project에서 시작
auto import OK (build.gradle 파일 변경할 때 마다 바로바로 변경 : dependency 추가 등)
원하는 build 형태의 spring boot project를 생성해준다. (dir 형태로!)
3. 스프링 프로젝트의 구조
gradle java 기본 프로젝트 구조와 동일하다
저장 파일
파일 경로
설명
소스 코드
src/main/java
-
소스 리소스
src/main/resource
java application에서 resources 기준으로 아래 것들을 참조 가능 (classpath)
테스트 코드
src/test/java
-
테스트 리소스
src/test/resource
test 관련 리소스를 만들 수 있다
메인 애플리케이션 위치 (@SpringBootApplication) : 기본 패키지 package com.jyami 프로젝트가 쓰고있는 가장 최상위 패키지! > why? 컴포넌트 스캔을 하기 때문
com.jyami에서부터 시작을 해서, 그 아래에 있는 파일들을 스캔해서 bean으로 등록한다.
src/main/java 위치에 넣으면 모든 패키지를 스캔하므로
만약 java>com.hello 패키지가 있고, 그안에 메인 애플리케이션이 아닌 java파일이 있으면, 그 java파일은 component 스캔이 이루어지지 않는다.
1. Introduction to Spring Boot
1-1. Spring Boot Start
Features
It's a tool that helps you build production-level applications, not just toy projects.
opinated view : This refers to the conventions that Spring Boot has (widely used configurations)
It provides default configurations not only for the Spring platform but also for other libraries (like tomcat) out of the box.
Goals
Provides faster and broader usability for all Spring development.
Provides convention-based configurations without having to set everything up manually. But you can easily and quickly change these settings to match your requirements. (This is the reason to use Spring Boot)
Provides non-functional configurations as well. Beyond features needed for business logic, it also covers non-functional features!
Does not use XML and does not do code generation.
Spring Roo : It uniquely does code generation, but it's not widely used anymore. By not doing generation, things are easier, clearer, and simpler to customize. > The predecessor of Spring Boot
System Requirements
Spring Boot requires Java 8 or higher.
Supported servlet containers include Tomcat, Jetty, and Undertow.
2. Getting Started with Spring Boot
If you use IntelliJ Ultimate, it has a Spring Boot Initializer built in, but the Community edition does not. So you can create one using whichever build tool you prefer. We'll learn how to create a project without using the Spring Boot Initializer.
2-1. Starting from a Gradle Project
auto import OK (Applies changes immediately whenever the build.gradle file is modified: adding dependencies, etc.)
Typically, a project declares dependencies on one or more "starters". Spring Boot simplifies dependency declarations and provides a useful Gradle plugin for generating jars.
package com.jyami;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String args[]){
SpringApplication.run(Application.class, args);
}
}
Using the SpringBootApplication annotation to call the method that runs SpringApplication
Spring MVC requires many dependencies to run — so how did all those dependencies get pulled in?
We need to configure the MVC app (bean, tomcat, etc.)
: This is all configured in @SpringBootApplication. > EnableAutoConfiguration
In IntelliJ settings, go to Build, Execution, Deployment > Compiler > Annotation Processors and check Enable annotation processing to be able to use annotations built with Gradle.
Run
When you run the application and check the logs, you can see that Tomcat is already running on port 8080. If you open http://localhost:8080, you can confirm that the Tomcat web application is working. (Even though it shows an error page)
Build
gradle build
This builds the package. Since it's a Java project, a jar file is generated.
It generates a Spring Boot project in your desired build format. (As a directory structure!)
3. Spring Project Structure
It follows the same structure as a standard Gradle Java project.
File Type
File Path
Description
Source Code
src/main/java
-
Source Resources
src/main/resource
In a Java application, files below the resources directory can be referenced (classpath)
Test Code
src/test/java
-
Test Resources
src/test/resource
You can create test-related resources here
Main Application Location (@SpringBootApplication) : Default package package com.jyami This should be in the topmost package of the project! > Why? Because of component scanning.
Starting from com.jyami, it scans files underneath and registers them as beans.
If you place it directly under src/main/java, it would scan all packages.
If there's a package java>com.hello with a Java file that isn't the main application, that Java file will not be picked up by component scanning.
댓글
Comments