[JPA] AttributeConverter로 JPA 에서 Enum 다루기

유알·2023년 2월 16일
0

[DB/JPA]

목록 보기
1/7

Authority enum

public enum Authority {
    ROLE_USER, ROLE_ADMIN;
}

AuthorityConverter class

package com.oj.springchat.domain.member.domain;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

@Converter
public class AuthorityConverter implements AttributeConverter<Authority,String> {
    @Override
    public String convertToDatabaseColumn(Authority attribute) {
        return attribute.name();
    }

    @Override
    public Authority convertToEntityAttribute(String dbData) {
        return Authority.valueOf(dbData);
    }
}

Member class

package com.oj.springchat.domain.member.domain;

import com.oj.springchat.domain.model.Email;
import com.oj.springchat.domain.model.Name;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

@Entity
@Table(name = "member")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public class Member {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false)
    private Long id;


    @Embedded
    @AttributeOverride(name = "value", column = @Column(name = "email", nullable = false, unique = true, updatable = false, length = 50))
    private Email email;

    @Column(name = "password", nullable = false)
    private String password;

    @Embedded
    @AttributeOverride(name = "first", column = @Column(name = "first_name", nullable = false))
    @AttributeOverride(name = "middle", column = @Column(name = "middle_name", nullable = false))
    @AttributeOverride(name = "last", column =  @Column(name = "last_name", nullable = false))
    private Name name;

    @Column(name = "role", nullable = false)
    @Convert(converter = AuthorityConverter.class)
    private Authority authority;


    @CreationTimestamp
    @Column(name = "create_at", nullable = false, updatable = false)
    private LocalDateTime createAt;

    @UpdateTimestamp
    @Column(name = "update_at", nullable = false)
    private LocalDateTime updateAt;

    @Builder
    public Member(Email email, String password, Authority authority, Name name) {
        this.email = email;
        this.password = password;
        this.authority = authority;
        this.name = name;
    }


}
profile
더 좋은 구조를 고민하는 개발자 입니다

0개의 댓글