Kotlin으로 Springboot 를 해보면서 정상적으로 JPA가 연관관계를 정상적으로 매핑하고 동작하는지 궁금하였다!
그래서 간단한 게시글에 댓글을 구현하여서, Post 엔티티와 Comment 엔티티를 일대다 관계로 매핑을 해보자!
1. Post Entity
@Entity
@Table(name = "post")
class Post(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "post_id")
var id: Long = 0,
var title: String,
var contents: String,
@ColumnDefault("0")
var view: Long = 0,
@Enumerated(EnumType.STRING)
var isDeleted: IsDeleted = IsDeleted.N,
@JsonManagedReference
@OneToMany(mappedBy = "post", cascade = [CascadeType.ALL], orphanRemoval = true)
private val comment: Set<Comment> = HashSet<Comment>()
)
2. Comment Entity
@Entity
class Comment(
@Id
@Column(name = "comment_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private var id: Long = 0,
@lombok.Setter
private val content: String,
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private val post: Post,
@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition = "char default 'N'")
private val isDeleted: IsDeleted = IsDeleted.N
)
3. 연관관계 확인 및 FetchType.LAZY 및 orphanRemoval=true 옵션확인!!
3-1 연관관계 ERD 확인
위와 같이 Comment 엔티티가 Post_Id를 외래키로 가지게 하며 엔티티를 구성을 하였다.
spring.jpa.generate-ddl=true 옵션을 true로 설정하여 해당 데이터를 근거로 서버 시작 시점에 DDL문을 생성하여 DB에 정상적으로 테이블들을 생성하는지 확인해보았다.
생성된 테이블의 ERD를 확인하여보자!! 정상적으로 외래키를 가지며 일대다의 ERD를 가지는 모습을 볼 수 있었다!!!
3-2 FetchType.LAZY (지연로딩) 옵션 확인!!
단순히 post 객체를 조회하였을 때.
Hibernate: select post0_.post_id as post_id1_1_0_, post0_.contents as contents2_1_0_, post0_.is_deleted as is_delet3_1_0_, post0_.title as title4_1_0_, post0_.view as view5_1_0_ from post post0_ where post0_.post_id=?
쿼리를 확인하면, 프록시 객체를 초기화하지않는 쿼리를 확인할 수 있었습니다.!
3 - 3 orphanRemoval = true 옵션도 정상적으로 동작하는지 테스트 해보자!!
위와 같이 Id = 1인 post와 그 Id를 외래키를 가지고 있는 comment 테이블이다.
한번 글을 삭제해보자!
ㅎㅎ 정상적으로 해당 게시글의 주키를 외래키로 가지고 있던 comment 까지 삭제되는 모습을 확인할 수 있었다!
모든 소스코드는 Github 에서 확인할 수 있습니다.
https://github.com/Hyeongwon-up/Kotlin-Server-Side-Lab
GitHub - Hyeongwon-up/Kotlin-Server-Side-Lab: Springboot + Kotlin + JPA + Kotest 놀이터 😈
Springboot + Kotlin + JPA + Kotest 놀이터 😈. Contribute to Hyeongwon-up/Kotlin-Server-Side-Lab development by creating an account on GitHub.
github.com
'Spring > Kotlin' 카테고리의 다른 글
[Kotlin+Springboot+JPA] Exception Handling by Kotlin (0) | 2021.08.31 |
---|---|
[SpringBoot + Kotlin + JPA] 간단한 게시글 CRUD REST Api 구현. (0) | 2021.08.08 |
[Springboot + Kotlin] Slack 채널 메세지 전송 연동. (0) | 2021.08.06 |
[Kotlin + Springboot + Kotest] Kotest 알아보자. (0) | 2021.08.01 |
[Kotlin + Springboot + JPA] Entity 생성에 관하여. (0) | 2021.07.28 |