๋๊ธ api ๊ตฌํํ๊ธฐ
๊ฒฐ๊ณผ
์ํฐํฐ(Entity)
> ํ์ผ๋ช : Coment.java
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "noticeComment")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "notice_id")
private NoticeEntity notice;
private String userName;
private String content;
}
import ๋ฌธ:
- ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ฐ ํจํค์ง๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
@Getter, @Setter, @AllArgsConstructor, @NoArgsConstructor:
- Lombok ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ์ด๋ ธํ ์ด์ ์ผ๋ก, ๊ฐ๊ฐ ํ๋์ ๋ํ getter, setter ๋ฉ์๋๋ฅผ ์๋ ์์ฑํ๊ณ , ๋ชจ๋ ํ๋๋ฅผ ์ธ์๋ก ๋ฐ๋ ์์ฑ์์ ์ธ์ ์๋ ์์ฑ์๋ฅผ ์์ฑํฉ๋๋ค.
@Entity:
- JPA(Entity Manager๋ฅผ ์ฌ์ฉํ๋ Java ORM ๊ธฐ์ )์์ ์ํฐํฐ์์ ๋ํ๋ ๋๋ค.
@Table(name = "noticeComment"):
- ๋ฐ์ดํฐ๋ฒ ์ด์ค์์ ํด๋น ์ํฐํฐ๋ฅผ ๋งคํํ ํ ์ด๋ธ์ ์ด๋ฆ์ ์ง์ ํฉ๋๋ค. ์ฌ๊ธฐ์๋ "noticeComment" ํ ์ด๋ธ์ ๋งคํ๋ฉ๋๋ค.
@Id, @GeneratedValue(strategy = GenerationType.IDENTITY):
- ํด๋น ํ๋๊ฐ ์ํฐํฐ์ ์ฃผํค(identity key)์์ ๋ํ๋ ๋๋ค. GenerationType.IDENTITY ์ ๋ต์ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์์กดํ์ฌ ์ฃผํค๋ฅผ ์์ฑํ๋ ๋ฐฉ์์ ๋๋ค.
private Long id;:
- ๋๊ธ์ ์๋ณ์๋ฅผ ๋ํ๋ด๋ ํ๋์ ๋๋ค.
@ManyToOne(fetch = FetchType.LAZY), @JoinColumn(name = "notice_id"):
- NoticeEntity์์ ๋ค๋์ผ(N:1) ๊ด๊ณ๋ฅผ ๋ํ๋ ๋๋ค. fetch = FetchType.LAZY๋ ์ฐ๊ด๋ ์ํฐํฐ๋ฅผ ์ง์ฐ๋ก๋ฉํ๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค. @JoinColumn(name = "notice_id")๋ ์ธ๋ ํค๋ฅผ ์ง์ ํฉ๋๋ค.
- private NoticeEntity notice;:
- ํด๋น ๋๊ธ์ด ์ด๋ค ๊ณต์ง์ฌํญ์ ์ํ๋์ง๋ฅผ ๋ํ๋ด๋ ํ๋์ ๋๋ค.
- private String userName;:
- ๋๊ธ์ ์์ฑํ ์ฌ์ฉ์์ ์ด๋ฆ์ ๋ํ๋ด๋ ํ๋์ ๋๋ค.
- private String content;:
- ๋๊ธ์ ๋ด์ฉ์ ๋ํ๋ด๋ ํ๋์ ๋๋ค.
DTO
CommentDTO๋ ์ฃผ๋ก ์ปจํธ๋กค๋ฌ๋ ์๋น์ค ๊ณ์ธต์์ ์ํฐํฐ๊ฐ ์๋ ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๊ณ ๋ฐ์ ๋ ์ฌ์ฉ๋ฉ๋๋ค. ์ด๋ฅผ ํตํด ์ํฐํฐ์ ์ ๋ณด๋ฅผ ํด๋ผ์ด์ธํธ์ ๋ ธ์ถ์ํค์ง ์๊ณ ํ์ํ ์ ๋ณด๋ง์ ์ ๋ฌํ ์ ์์ต๋๋ค.
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CommentDTO {
private Long id; // ๋๊ธ์ ์๋ณ์
private String userName; // ๋๊ธ์ ์์ฑํ ์ฌ์ฉ์ ์ด๋ฆ
private String content; // ๋๊ธ ๋ด์ฉ
}
CommentDTO๋ ์ฃผ๋ก ์ปจํธ๋กค๋ฌ๋ ์๋น์ค ๊ณ์ธต์์ ์ํฐํฐ๊ฐ ์๋ ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๊ณ ๋ฐ์ ๋ ์ฌ์ฉ๋ฉ๋๋ค. ์ด๋ฅผ ํตํด ์ํฐํฐ์ ์ ๋ณด๋ฅผ ํด๋ผ์ด์ธํธ์ ๋ ธ์ถ์ํค์ง ์๊ณ ํ์ํ ์ ๋ณด๋ง์ ์ ๋ฌํ ์ ์์ต๋๋ค.
์์ CommentDTO๋ฅผ ์ฌ์ฉํ์ฌ ๋๊ธ ์กฐํ ์ DTO๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฐํํ ์ ์์ต๋๋ค. ์๋๋ ์๋น์ค๋ ์ปจํธ๋กค๋ฌ์์ CommentDTO๋ฅผ ์ฌ์ฉํ์ฌ ๋๊ธ์ ์กฐํํ๊ณ ๋ฐํํ๋ ์ฝ๋ ์ ๋๋ค.