[게시판 프로젝트] 도메인 설계하기 - Java 클래스로 도메인 표현하기
2024. 8. 15. 22:27ㆍ웹 개발/프로젝트
도메인 ERD 다이어그램을 토대로,
Java 클래스에 도메인을 표현한다.
Article Class
lombok 설정
@Getter // class 레벨로 Setter를 걸지 않음
@Table(indexes = {
})//사이즈가 너무 큰 본문은 보통 인덱스를 걸지 않음 - ElasticSearch와 같은 검색엔진의 도움을 받음
@EntityListeners(AuditingEntityListener.class)//auditing 기능을 동작하게 함
API 설계했던 토대로 변수를 작성
@ToString.Exclude
/*ToString includes lazy loaded fields and/or associations.
This can cause performance and memory consumption issues
-> circular referencing 문제가 일어날 수 있음
collection들어가서 articleComment 안으로 들어가서 또 toString을 보려고 하는데,
articleComment안에 toString이 있어서 또 Article이 있어서 Article 보고 무한 반복*/
private final Set<ArticleComment> articleComments = new LinkedHashSet<>();
//이 Article에 연동되어있는 comment는 중복을 허용하지 않고 리스트로 모아서 보여주겠다.
@EntityListeners(AuditingEntityListener.class)//auditing 기능 동작하게 함
@Entity 클래스에서 꼭 적어줘야하는 사항
protected Article() {
//모든 hibernate 구현체를 사용하는 JPA entity는 기본생성자를 가지고 있어야함
//평소에 오픈하지 않을 것이기 때문에 protected로 설정함
}
private Article(String title, String content, String hashtag) {
//자동 생성되지 않고, 원래 도메인과 연관된 부분만 생성자로 만들 수 있게 유도함
this.title = title;
this.content = content;
this.hashtag = hashtag;
}
public static Article of(String title, String content, String hashtag) {
//new 안쓰고 생성자 메소드 사용할 수 있도록
return new Article(title,content,hashtag);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Article article)) return false;
return id != null && id.equals(article.id);
}
/*
컬렉션에서 사용할 때 동일성, 동등성 검사 -> EqualsHashCode
unique한 id만 가지고 hashing을 하면 됨
엔티티를 DB에 영속화시키고 연결짓고 사용하는 환경에서
서로 다른 두 엔티티가 같은 조건이 무엇인가에 대한 질문에 Equals가 답을 함
<return id != null의 뜻>
id != mull : 아직 영속화되지 않은 엔티티는 그 내용이 동등하다고 하더라도 동등성 검사는 탈락한다.
pattern matching for instance Java 14
*/
@Override
public int hashCode() {
return Objects.hash(id);
}
ArticleComment Class
- 메타데이터는 별개의 클래스를 작성하여 빼줌 -> @EntityListeners 도 더이상 필요없음
- extends AuditingFields : 상속으로 연계시킴
AuditingFields
JPAConfig
JPA에 대한 설정만 따로 모아보는 Configuration Class
@EnableJpaAuditing //Auditing 기술을 사용하겠다는 의미
@Configuration
public class JpaConfig {
@Bean
public AuditorAware<String> auditorAware(){ // auditing할 때 사람 이름(String)을 넣어주기 위한
return () -> Optional.of("username"); //TODO: 스프링 시큐리티로 인증 기능을 붙이게 될때, 수정하자
}
}
'웹 개발 > 프로젝트' 카테고리의 다른 글
[게시판 프로젝트] API 구현(2) - Querydsl을 통해서 세부 검색 기능 구현 (0) | 2024.08.16 |
---|---|
[게시판 프로젝트] repository, JPAConfig 생성 (0) | 2024.08.15 |
[게시판 프로젝트] IntelliJ spring boot DB 접근 설정하기 - MySQL (0) | 2024.08.15 |
[게시판 프로젝트] 도메인 설계하기 - github과 draw.io 연동하여, ERD 그리기 (0) | 2024.08.15 |
[게시판 프로젝트] 기획하기 - 유즈케이스 작성하기/API 설계하기 (0) | 2024.08.14 |