백엔드/JPA

[ JPA ] 5-3. Entity Relations ( 1:N @OneToMany )

Reference. 한 번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지 Online

이전 글

1. 속성

  • @OneToMany 속성
    • fetch: 트랜잭션과 관련된 속성 ( FetchType.EAGER 변경 ), 설정하지 않으면 오류 발생
    @OneToMany(fetch = FetchType.EAGER)
        private List<UserHistory> userHistories = new ArrayList<>();
  • @JoinColumn 엔티티 속성이 조인에 대상인지 지정
    • name: 참조할 테이블의 어떤 컬럼으로 조인 할 것인지 지정
      name을 지정하지 않으면 매핑테이블(user_user_histories)이 자동 생성 됌
    • insertable, updatable: 참조 테이블을 insert, update 처리 여부 (default: true)
      insertable, updatable을 설정하지 않으면 cascade, 트랜잭션
      JPA에서 자동으로 처리하는 것이 많아, 예상치 못한 오작동과 쿼리를 발생
    //@JoinColumn 사용 전
    public class User extends BaseEntity{
    		...
    		@OneToMany(fetch = FetchType.EAGER)
        private List<UserHistory> userHistories = new ArrayList<>();
    }
    
    //*문제발생: user_user_histories 생성 됌
    Hibernate: 
        
        create table user_user_histories (
           user_id bigint not null,
            user_histories_id bigint not null
        )

2. 최종 실행결과

User.java
public class User extends BaseEntity{
		...
		@OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "userId", insertable = false, updatable = false)
    private List<UserHistory> userHistories = new ArrayList<>();
}
UserHistory.java
public class UserHistory extends BaseEntity{
		@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long userId;
		...
}
실행결과
Hibernate: 
    
    create table user (
       id bigint generated by default as identity,
        created_at timestamp,
        updated_at timestamp,
        email varchar(255),
        gender integer,
        name varchar(255),
        primary key (id)
    )
Hibernate: 
    
    create table user_history (
       id bigint generated by default as identity,
        created_at timestamp,
        updated_at timestamp,
        email varchar(255),
        name varchar(255),
        user_id bigint,
        primary key (id)
    )

//조인하지 않고 조회 함(user 조회 -> user_history 조회)
Hibernate: 
    select
        user0_.id as id1_3_,
        user0_.created_at as created_2_3_,
        user0_.updated_at as updated_3_3_,
        user0_.email as email4_3_,
        user0_.gender as gender5_3_,
        user0_.name as name6_3_ 
    from
        user user0_ 
    where
        user0_.email=?

Hibernate: 
    select
        userhistor0_.user_id as user_id6_4_0_,
        userhistor0_.id as id1_4_0_,
        userhistor0_.id as id1_4_1_,
        userhistor0_.created_at as created_2_4_1_,
        userhistor0_.updated_at as updated_3_4_1_,
        userhistor0_.email as email4_4_1_,
        userhistor0_.name as name5_4_1_,
        userhistor0_.user_id as user_id6_4_1_ 
    from
        user_history userhistor0_ 
    where
        userhistor0_.user_id=?