데이터베이스 설계 시, 단일로 들어가야하는 조건을 넣어야 하는 경우 유니크 제약조건을 넣는다.
예를 들어 회원의 아이디 또는 이메일과 같이 로그인 시 중복되지 않아야하는 경우를 말한다.
JPA 코드 상에서 단일 조건의 경우
@Entity
@Table(name = "UNIQUE_ENTITY")
@NoArgsConstructor
public class UniqueEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name = "unique_one", unique = true)
private Long uniqueOne;
@Column(name = "unique_two")
private Long uniqueTwo;
}
@Column 어노테이션에 unique = true 설정을 추가한다.
JPA 코드 상에서 두개 이상의 조건(복합키)인 경우
@Entity
@Table(name = "UNIQUE_ENTITY",
uniqueConstraints={
@UniqueConstraint(
name="contstraintName",
columnNames={"unique_one", "unique_two"} // DB 상의 column name 을 작성해야한다. (변수명X)
)
})
@NoArgsConstructor
public class UniqueEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name = "unique_one")
private Long uniqueOne;
@Column(name = "unique_two")
private Long uniqueTwo;
}
@Table 어노테이션 안에 제약조건 이름과 컬럼 이름을 작성해주면 된다.
이때 columnNames 안에 컬럼 명은 변수명으로 작성하는 것이 아니여서 DB 상의 컬럼 명 변경 시 같이 변경해줘야한다.
(나는 저런 부분이 변수명 작성인지 DB 컬럼명 작성인지 매번 헛갈려서 이 글에 기록용으로 남겨두려한다.)
728x90
'DEV > Spring' 카테고리의 다른 글
[Spring] Spring Security 란? (0) | 2023.07.26 |
---|---|
[Spring] Exception Handler (with. Spring Data Rest) (1) | 2023.07.12 |
[Spring] Spring Data Rest 란? (0) | 2023.07.10 |
[JPA] Repository 인터페이스 (0) | 2023.04.19 |
[Spring] Spring Framework 란? (0) | 2023.03.31 |