Home Composite Key Setting
Post
Cancel

Composite Key Setting

복합키 설정

  • 공통 조건
    • 복합키는 별도의 클래스
    • Serializable implements
    • EqualsAndHashCode 구현
    • 기본 생성자
    • 클래스의 공개 범위는 public
  • @IdClass
    • Entity에 복합키를 매핑해줄 떄 사용하는 어노테이션
    • 설계상 RDBS에 가깝다.
  • @EmbeddedId
    • Entity에 복합키를 매핑해줄 때 사용하는 어노테이션
    • 설계상 객체지향에 가깝다.


@IdClass

  • Entity 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Entity
@Getter
@Setter
@ToString
@Table(name = "author")
@IdClass(AuthorId.class)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Author {

  @Id
  private String authorId;

  @Id
  private String authorName;

  private String text;

  public Author(String authorId, String authorName, String text) {
    this.authorId = authorId;
    this.authorName = authorName;
    this.text = text;
  }

}


  • IdClass 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@NoArgsConstructor
@AllArgsConstructor
public class AuthorId implements Serializable {
  private String authorId;
  private String authorName;

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    AuthorId givenObject = (AuthorId) o;
    return authorId.equals(givenObject.authorId) && authorName.equals(givenObject.authorName);
  }

  @Override
  public int hashCode() {
    return Objects.hash(authorId, authorName);
  }
}


@EmbeddedId

  • Entity 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Entity
@Getter
@Setter
@ToString
@Table(name = "company")
@IdClass(CompanyId.class)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Company {

    @EmbeddedId
    private CompanyId companyId;

    private String text;

}


  • EmbeddedId 코드
1
2
3
4
5
6
7
8
@Embeddable
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class CompanyId implements Serializable {
    private String companyId;
    private String companyName;
}
This post is licensed under CC BY 4.0 by the author.