ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • @ManyToOne(optional=false)/@JoinColumn(nullable=false)
    jpa/Hibernate 2023. 5. 28. 20:55

    MEMBER,TEAM.txt
    0.00MB

    Team

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Entity
    class Team {
    	@Id
    	private Integer id;
    	private String name;
    
    	@OneToMany(mappedBy = "team")
    	private List<Member> member;
    }

     

    Member

    @Getter
    @Setter
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Entity
    class Member {
    	@Id
    	private Integer id;
    	private String name;
    
    	@ManyToOne
    	@JoinColumn(name = "team_id")
    	private Team team;
    }

    1. 기본

     

    create시 fk 컬럼인 team_id에 not null제약이 걸리지 않는다.

     

    다음의 쿼리를 통해 테스트 데이터 insert후 join을 비교해보면

    create table member (id integer not null, name varchar(255), team_id varchar(255), primary key(id));
    create table team (id integer not null, name varchar(255), primary key(id));
    alter table member add constraint member_team_id_fk foreign key (team_id) references team(id);
    insert into team values(1, 'team1');
    insert into team values(2, 'team2');
    insert into team values(3, 'team3');
    insert into member values(1, 'mem1', null);
    insert into member values(2, 'mem2', null);
    insert into member values(3, 'mem3', null);
    insert into member values(4, 'mem4', null);
    insert into member values(5, 'mem5', null);
    insert into member values(6, 'mem6', null);
    insert into member values(7, 'mem7', null);
    insert into member values(8, 'mem8', null);
    insert into member values(9, 'mem9', null);
    insert into member values(10, 'mem10', null);
    insert into member values(11, 'mem11', null);
    insert into member values(12, 'mem12', null);
    insert into member values(13, 'mem13', null);
    insert into member values(14, 'mem14', null);
    insert into member values(15, 'mem15', null);
    update member set team_id = 1 where id  in (1,2,3,4,5);
    update member set team_id = 2 where id  in (6,7,8,9,10);

     

    위와 같이 fk컬럼이 null인 경우도 존재하므로 left join(left outer join)을 사용해서 값을 가져온다고 한다.


    2. 둘중 하나이상 false로 설정된 경우

    @ManyToOne(optional = false)
    @JoinColumn(name = "team_id")
    //또는
    @ManyToOne
    @JoinColumn(name = "team_id", nullable = false)
    //또는
    @ManyToOne(optional = false)
    @JoinColumn(name = "team_id", nullable = false)
    private Team team;

     

    create시 fk컬럼에 not null제약이 걸린다.

     

    fk컬럼이 null인 경우가 없으므로 inner join(left inner join)을 통해 값을 가져온다고 한다.

    또한 Member객체 team필드 미셋팅 상태로 persist시 에러가 발생


    https://feco.tistory.com/102

     

    NULL 제약 조건과 조인 전략

    JPA는 매핑관계의 필수 여부에 따라 실제 데이타베이스로 보내는 SQL 구문이 달라진다선택적 관계 @Entity public class Member { //... @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "teamId") private Team team; //... }

    feco.tistory.com

     

    댓글

Designed by Tistory.