본문 바로가기

dev/Spring

spring data jpa에서 enum 사용 방법

엔티티 클래스 중, Enum 값을 가지는 필드에 @Enumerated 를 붙여준다.

@Enumerated에는 EnumType.STRING 혹은 EnumType.ORDINAL을 인자로 전달할 수 있다.

둘의 차이는 다음과 같다.


@Enumerated(EnumType.STRING) Rating rating the value of rating.name() is written and read from the corresponding database column; e.g. G, PG, PG13


@Enumerated(EnumType.ORDINAL) Rating rating the value of rating.ordinal() is written and read from the corresponding database column; e.g. 0, 1, 2


예시 코드는 다음과 같다.


@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
@DynamicUpdate
@Table(name = "authority")
public class Authority {
@Id
@Enumerated(EnumType.STRING) // @Enumberated를 붙여준다.
private AuthorityName name; // name은 user, admin 둘 중 하나의 값을 가져야 한다.
private String description;

@Builder
public Authority(AuthorityName name, String description){
this.name = name;
this.description = description;
}
}


[참조]

http://tomee.apache.org/examples-trunk/jpa-enumerated/