Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 26 | 27 | 28 |
Tags
- 스프링부트오류
- Error creating bean with name
- json
- git
- 복합키
- jwt메서드
- 스프링 부트 기능
- jpa에러
- @IdClass
- 인텔리제이
- uncheck Exception
- jpa회원가입
- JPA
- queryDSL
- github
- REST API 규칙
- Filter
- Q 클래스
- JoinColumn
- REST란
- 스프링 부트 공식 문서
- json gson 차이
- Spring Spring boot 차이
- spring서버
- Unsatisfied dependency
- JPA주의사항
- 최종 프로젝트
- 빈생성안됨
- 1차캐시
- ERD 작성
Archives
- Today
- Total
Everyday Dev System
JPA 복합키 설정하기 - @EmbeddedId 본문
복합키 위에 @EmbeddedId를 기재하여 사용하는 방법이다.
<< 중요한 포인트 >>
1. @Embeddable 과 @EmbeddedId와 매핑
2. @MapsId("user_id") 와
@Column(name="user_id") 이 매핑이 되므로, 값이 동일
복합키 UserChannelId 클래스 코드
1. @Embeddable → 클래스 위에 어노테이션 기재
2. @Column(name="user_id") → UserChannel 의 @MapsId("user_id") 속성값과 동일해야 한다.
package me.chaeyoung.jpa.userChannel;
import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Objects;
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Embeddable
public class UserChannelId implements Serializable {
// Serializable 는 id로 설정하기 위해 반드시 필요함.
@Column(name="user_id") // UserChannel 의 @MapsId 속성값과 동일해야 함.
private Long userId;
@Column(name="channel_id") // UserChannel 의 @MapsId 속성값과 동일해야 함.
private Long channelId;
@Override
public boolean equals(Object e){
if (this == e) return true;
if (e == null || getClass() != e.getClass()) return false;
UserChannelId userChannelId = (UserChannelId) e;
return Objects.equals(getUserId(), userChannelId.getUserId()) && Objects.equals(getChannelId()
, userChannelId.getChannelId());
}
@Override
public int hashCode() {
return Objects.hash(getUserId(), getChannelId());
}
}
UserChannel 엔티티 클래스 코드
1. @EmbeddedId → 복합키 클래스 멤버변수 앞에 기재
@EmbeddedId
private UserChannelId userChannelId;
2. @MapsId("user_id") → 복합키 클래스 내에 멤버 변수명과 동일하게 명시
package me.chaeyoung.jpa.userChannel;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import me.chaeyoung.jpa.channel.Channel;
import me.chaeyoung.jpa.user.User;
// lombok
@Getter
@NoArgsConstructor
// jpa
@Entity
public class UserChannel {
@Builder
public UserChannel(User user, Channel channel){
this.user = user;
this.channel = channel;
}
@EmbeddedId
private UserChannelId userChannelId;
@ManyToOne
@MapsId("user_id")
private User user;
@ManyToOne
@MapsId("channel_id")
private Channel channel;
}
'내배캠 주요 학습 > JPA 심화' 카테고리의 다른 글
JpaRepository 기능 제한하기 (0) | 2023.07.31 |
---|---|
Cascade.REMOVE 와 orphanRemoval=true 차이 (0) | 2023.07.31 |
JPA 복합키 설정하기 - @IdClass (0) | 2023.07.31 |
JPA) N : 1 관계 맵핑 (Thread : Channel : User) (0) | 2023.07.31 |
JPA) N : 1 관계 맵핑 (thread : Channel) (0) | 2023.07.31 |