특정 매핑 테이블을 구현하면서 복합키로 PK를 생성했던 케이스를 정리한 글입니다.
package com.arton.backend.follow.adapter.out.persistence.entity;
import com.arton.backend.infra.shared.BaseEntity;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@Entity
@Table(name = "Follow", uniqueConstraints = @UniqueConstraint(columnNames = {"from_user", "to_user"}))
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@IdClass(FollowEntity.PK.class)
public class FollowEntity extends BaseEntity {
@Id
@Column(name = "from_user", insertable = false, updatable = false)
private Long fromUser;
@Id
@Column(name = "to_user", insertable = false, updatable = false)
private Long toUser;
@Builder
public FollowEntity(LocalDateTime createdDate, LocalDateTime updatedDate, Long fromUser, Long toUser) {
super(createdDate, updatedDate);
this.fromUser = fromUser;
this.toUser = toUser;
}
public static class PK implements Serializable {
Long fromUser;
Long toUser;
}
}
static 대신 직접 클래스를 따로 만들어서 사용했던 케이스 입니다.
package com.arton.backend.zzim.domain;
import lombok.*;
import java.io.Serializable;
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Getter
@EqualsAndHashCode
public class PerformanceZzimCompoundKey implements Serializable {
private Long performance;
private Long user;
}
package com.arton.backend.zzim.adapter.out.persistence.entity;
import com.arton.backend.infra.shared.BaseEntity;
import com.arton.backend.performance.adapter.out.persistence.entity.PerformanceEntity;
import com.arton.backend.user.adapter.out.persistence.entity.UserEntity;
import com.arton.backend.zzim.domain.PerformanceZzimCompoundKey;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Entity
@Table(name = "Performance_Zzim")
@ToString
@IdClass(PerformanceZzimCompoundKey.class)
public class PerformanceZzimEntity extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private UserEntity user;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "performance_id")
private PerformanceEntity performance;
public void setUser(UserEntity user) {
this.user = user;
if (!user.getPerformanceZzims().contains(this)) {
user.getPerformanceZzims().add(this);
}
}
@Builder
public PerformanceZzimEntity(LocalDateTime createdDate, LocalDateTime updateDate, Long id, UserEntity user, PerformanceEntity performance) {
super(createdDate, updateDate);
this.id = id;
this.user = user;
this.performance = performance;
}
}