클래스를 생성할 때마다 id 나 name 처럼 중복되는 필드를 쉽게 처리하고 싶다면 어떤 방법이 있을까?
즉, DB는 유지하고 객체의 필드만 메서드처럼 공통으로 묶어두고 가져다 사용하는 방법은 없을까?
이럴 때 사용하는 방법이 @MappedSuperclass을 사용하는 것이다.
적용
@MappedSuperclass
@Getter @Setter
public class BaseEntity {
private String createdBy;
private LocalDateTime localDateTime;
private String lastModifiedBy;
private LocalDateTime getLastModifiedDate;
}
먼저 공통 로직을 하나의 클래스에 모아둔다.
@Entity
@Getter @Setter
public class Team extends BaseEntity{
@Id @GeneratedValue
@Column(name = "team_id")
private Long id;
private String name;
@OneToMany(mappedBy = "team") // 저는 team 컬럼에 의해 관리되는 필드입니다.
private List<Member> members = new ArrayList<>();
}
이후 생성한 BaseEntity를 상속받기만 하면 된다.
테스트코드 작성
실제 DB에도 위 Team 엔티티의 필드가 적용되는지 확인해보자.
예외따윈 가볍게 무시
예외는 내가 실수로 테이블 이름을 order 에약어로 설정해서 그렇다ㅋㅋ..
@Test
public void super_class_test() throws Exception {
EntityTransaction tx = em.getTransaction();
tx.begin();
try{
Team team = new Team();
team.setName("team");
team.setCreatedBy("이게 팀이야");
team.setCreatedDate(LocalDateTime.now());
em.persist(team);
em.flush();
em.clear();
em.find(Team.class, team.getId());
tx.commit();
} catch(Exception e) {
tx.rollback();
} finally {
em.close();
}
}
테스트도 끗 !
정리
이건 테이블이나 엔티티와 관련이 없고, 단순히 공통으로 사용하는 매핑 정보를 모아놓고 사용하귀 위한 기능이다.