728x90
도메인설계를 하다보면 유저와 할일,알림,이벤트 의 관계도 동일할 뿐더러, 엔티티간의 데이터 중복이 발생한다.
이를 가독성좋게, 관리하기 편하게 테이블은 하나로 두되, 코드로 직접 감싸서 용도에 맞는 도메인 3개로 쪼갠다.
아래와 같이 기존 도메인을 가지고 공통된 부분을 Schedule 에 클래스에 필드로 담고 , Event, Notification,Task 는 ScheduleType의 Enum타입으로 필드변환
Task
Event - SchedulType - Schedul 의 계층구조이다.
Notification
@Builder(access = AccessLevel.PRIVATE)
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "schedules")
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime startAt;
private LocalDateTime endAt;
private String title;
private String description;
@JoinColumn(name = "writer_id")
@ManyToOne
private User writer;
@Enumerated(EnumType.STRING) ##Enum 타입으로 하위계층을 관계를 가진다.
private ScheduleType scheduleType;
private LocalDateTime createdAt = LocalDateTime.now();
//어떤 데이터로 부터 각 enum 타입에 객체를 만들때 필요
public static Schedule event(String title,
String description, LocalDateTime startAt,
LocalDateTime endAt, User writer) {
return Schedule.builder()
.startAt(startAt)
.endAt(endAt)
.title(title)
.description(description)
.writer(writer)
.scheduleType(ScheduleType.EVENT)
.build();
}
public static Schedule task(String title, String description, LocalDateTime taskAt,
User writer) {
return Schedule.builder()
.startAt(taskAt)
.title(title)
.description(description)
.writer(writer)
.scheduleType(ScheduleType.TASK)
.build();
}
public static Schedule notification(String title, LocalDateTime notifyAt, User writer) {
return Schedule.builder()
.startAt(notifyAt)
.title(title)
.writer(writer)
.scheduleType(ScheduleType.NOTIFICATION)
.build();
}
//도메인 변경가능하기 위한 메소드
public Task toTask() {
return new Task(this);
}
public Event toEvent() {
return new Event(this);
}
public Notification toNotification() {
return new Notification(this);
}
}
BaseEntity , Auditing 적용
BaseEntity : 도메인 클래스들의 중복된 필드값을 따로 클래스로 만들어 적용
auditing : jpa에서 영속화 되기전에 미리 자동셋팅 ( 생성시간,수정시간.. 등)
상속관계 설정 , 메인클래스 @EnableJpaAuditing 설정도 잊지말기를...
@Getter
@MappedSuperclass
//상속을 한 클래스가 부모의 속성만 따서 자식클래스가 된다.
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
//AuditingEntityListener 가 jpa 영속화 되기전에 @CreatedDate @LastModifiedDate
//설정을 해준다.
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate
private LocalDateTime createdAt = LocalDateTime.now();
@LastModifiedDate
private LocalDateTime updatedAt;
public BaseEntity(Long id) {
this.id = id;
}
}
728x90
'calendar' 카테고리의 다른 글
event 생성(시간겹치는 로직, 이메일발송) (0) | 2023.03.18 |
---|---|
ArgumentResolver를 이용한 권한처리 (0) | 2023.03.18 |
Task 생성 (0) | 2023.03.18 |
Bcrypt 암호화적용 (0) | 2023.03.17 |
calendar API설계 (0) | 2023.03.17 |