-
2022.02.07~13 기록장TIL 2022. 2. 6. 18:54
ToDo
- 미션 1 구현
- 좋아요 구현, 리팩토링
- 회원 탈퇴
Done
- 좋아요 구현, 리팩토링
- 미션 1 구현
Weekly goal
- 사이드 api 개발
- 책 읽기
- 도커, 쿠버, 밋업 준비. 서버 터짐
[jpa] 다른 정보와 함께 조회하기
단순히 엔티티를 조회하면서 다른 정보 ex) count 등을 함께 조회하고 싶을 경우가 있다.
엔티티 내부에 필드를 둬서 @Formula라던지 @transient 등을 써도 되지만 엔티티를 더럽히긴 싫을 경우이다.
애플리케이션 단에서 해도 되지만 엔티티도 같이 받고 싶을 경우 DTO로 받을 수 있다.
Spring-boot jpa how to find entity with max value
Lets tell I have two tables. CREATE TABLE user (ID int AUTO_INCREMENT,PRIMARY KEY (ID)); CREATE TABLE points (ID int AUTO_INCREMENT, user_id int, points int,PRIMARY KEY (ID)); How can I use sprin...
stackoverflow.com
DTO를 통해 받을 경우 문제가 생긴다. 엔티티를 가져오는 것이 아닌 해당 id값을 가져오는 문제가 생긴다.
여기서 list로 가져왔다면 n+1 문제가 생기는 것이다.
Avoid Entity In DTO Via Constructor Expression (no association)
If you prefer to read it as a blog-post containing the relevant snippets of code then check this post Description: Let's assume that we have two entities, Author and Book. There is no materialized association between them, but, both entities shares
www.linkedin.com
Avoid Fetching Entity In DTO Via Constructor Expression (No Associations)
Motivation: You should avoid fetching an entity in DTO via constructor expression to avoid potential N+1 issues. Description: Let's assume that we have two entities, Author and Book. There is no materialized association between them, but, both entities sha
persistencelayer.wixsite.com
본인도 n+1이 여기서 터졌기에 해결법을 찾아다니다 직접 entity manager를 호출하는 방법으로 갔다.
https://www.baeldung.com/jpa-return-multiple-entities
엔티티 매니저를 매번 생성하고 안 닫아주면 connection을 가지고 있어서 time out을 경험할 수 있다.
그래서 빈으로 등록된 entity manager를 사용했다.
연관관계가 없는 테이블 조인 방법
jpa 2.0 이후 버전부터는 oneToMany 쪽에 joinColunm을 붙여서 지원해준다.
문제는 테스트 코드에서 auto ddl create일 경우 외래 키를 만들어버려 테스트는 실패할 수 있다.
name = "reference_id", // 조인할 칼럼명
referencedColumnName = "id", // 현재 테이블의 키 값
이번에 구현 내용 중 한 테이블이 외래 키 없이 여러 테이블에서 사용될 칼럼이 존재하는 부분이 있었다.
예로 좋아요 테이블인데, 질문 좋아요, 댓글 좋아요 등을 저장하는 테이블이다.
이들은 각각 외래 키를 가지고 있는 것이 아닌 하나의 칼럼 ex) reference_id에 저장되고 type(varchar)로 구분된다.
Java Persistence/OneToMany - Wikibooks, open books for an open world
A OneToMany relationship in Java is where the source object has an attribute that stores a collection of target objects and if those target objects had the inverse relationship back to the source object it would be a ManyToOne relationship. All relationshi
en.wikibooks.org
일 다 ref_id는 질문, 답변 등의 id값이 들어오고 type으로 분류된다. 그렇기에 외래 키는 잡지 않고 작업한다.
예로 question은 one to many에 join column을 달고 name에는 반대편(support)의 바라볼 칼럼 이름, referencedColumnName에는 바라볼 컬럼과 매치될 컬럼 값을 넣는다.
외래 키 없이 일대다를 구성할 수 있다.
'TIL' 카테고리의 다른 글
2022.02.17~24 기록장 (0) 2022.02.16 2021.02.13~ 16기록장 (0) 2022.02.13 2022.01.28 기록장 (0) 2022.01.28 2022.01.23 기록장 (0) 2022.01.23 2022.01.17 기록장 (0) 2022.01.18