-
Notifications
You must be signed in to change notification settings - Fork 45
[Association - Step 1단계] OneToMany (FetchType.EAGER) #86
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
parkje0927
wants to merge
30
commits into
next-step:parkje0927
Choose a base branch
from
parkje0927:step1
base: parkje0927
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
856e473
feat: step1 - 기존 EntityMetaData 수정 및 EntityJoinMetaData 클래스 추가
parkje0927 f54f250
refactor: step1 - 기존 클래스 네이밍 변경 및 EntityMetaData 리팩토링
parkje0927 a27127b
refactor: step1 - 불필요한 클래스 삭제 및 변경
parkje0927 588fac7
feat: step1 - 엔티티 추가
parkje0927 63e5646
docs: step1 - 강의 내용 및 요구사항 문서 정리
parkje0927 3cc9e12
test: step1 - 기존 테스트 코드 개선, 중복 코드 추상 클래스로 정리
parkje0927 4600e06
test: step1 - join select 문 테스트 코드 추가
parkje0927 0047ab4
chore: step1 - 기존 메소드 유틸 클래스로 이관
parkje0927 82c0547
feat: step1 - CustomSelectQueryBuilder 추가
parkje0927 69ab69f
feat: step1 - EntityMetaData, EntityJoinMetaData 의 인터페이스 생성
parkje0927 75a7a28
refactor: step1 - 불필요한 클래스 삭제
parkje0927 de82331
chore: step1 - 주석 정리
parkje0927 a87eb1e
refactor: step1 - 불필요한 클래스 삭제
parkje0927 b423263
refactor: step1 - 메소드명 변경 및 객체에 책임을 위임하는 방법으로 변경
parkje0927 0a3c3a1
refactor: step1 - GenerationType 확인 메소드 추가
parkje0927 4314890
refactor: step1 - 리뷰 내용을 참고하여 EntityMetaData, EntityJoinMetaData 역할을 재정의
parkje0927 32f34f2
refactor: step1 - isTransient 필드 체크 로직을 초기화 시 처리하도록 수정
parkje0927 0e8b45e
refactor: step1 - EntityMetaData 초기화 시 EntityJoinMetaData 도 초기화 및 생성을…
parkje0927 ab58ef3
test: step1 - 테스트 추상화 범위 및 객체 초기화 방법 변경
parkje0927 a129006
chore: step1 - inline 정리
parkje0927 9f25689
refactor: step1 - 공통 상수 추가
parkje0927 6b169ca
refactor: step1 - 피드백 반영하여 수정
parkje0927 f29d118
feat: step1 - 요구사항 2번을 위해 loader 메소드 추가
parkje0927 3334c99
test: step1 - 테스트 static 변수 추가 및 join 엔티티화 테스트 코드 추가
parkje0927 2939e5b
refactor: step1 - 삼항연산자 if 문으로 수정
parkje0927 d61fa70
test: step1 - EntityMetaData 내 entityName 관련 테스트 추가
parkje0927 efb21b1
refactor: step1 - EntityMetaData 에서는 class 정보만 가지고 객체를 생성하도록 수정
parkje0927 0f6ac2a
test: step1 - 테스트 수정 및 기존 연관관계가 있는 findById 테스트 loader 테스트로 이관
parkje0927 19431c0
refactor: step1 - EntityJoinMetaData 에서도 entity 를 매개변수로 받지 않도록 수정
parkje0927 6509320
test: step1 - EntityJoinMetaData 수정에 따른 테스트 변경
parkje0927 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| ## 3/16 | ||
|
|
||
| ### 구현 | ||
| ```markdown | ||
| - Query | ||
| - Entity | ||
| -> 이렇게 2개의 패키지로 나누고, 1주차 미션과 약간 별개일 수 있다. | ||
|
|
||
| - SessionImpl 에 의해 session 을 계속 넣어서 다닌다. | ||
| - `return new StatefulPersistenceContext(this);` | ||
| - StatefulPersistenceContext | ||
| - `entitiesByKey` | ||
| - `collectionsByKey` | ||
| - AnnotationBinder 참고 | ||
|
|
||
| - InFlightMetadataCollector | ||
| - metadata 수집 | ||
| - 캐싱 설정(default = true) | ||
|
|
||
| ``` | ||
|
|
||
| ### logging | ||
| ```markdown | ||
| - logging.level.org.hibernate.boot=trace | ||
| - logging.level.org.hibernate=trace => 직접 api 실행해서 로깅 확인 | ||
| - Spring 은 로깅해서 확인해보는 것을 추천 => Spring 공부! | ||
| ``` | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # 1단계 - OneToMany (FetchType.EAGER) | ||
|
|
||
| ## 요구사항 1 - Join Query 만들기 | ||
|
|
||
| - Sql 쿼리 문을 수정해 보자 | ||
| ```java | ||
| public class CustomSelect { | ||
|
|
||
| } | ||
|
|
||
| ``` | ||
|
|
||
| ## 요구사항 2 - Join Query 를 만들어 Entity 화 해보기 | ||
|
|
||
| - FetchType.EAGER 인 경우 | ||
| ```java | ||
| public class SimplePersistenceContext implements PersistenceContext { | ||
|
|
||
| } | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| package entity; | ||
|
|
||
| import jakarta.persistence.Column; | ||
| import jakarta.persistence.Entity; | ||
| import jakarta.persistence.FetchType; | ||
| import jakarta.persistence.GeneratedValue; | ||
| import jakarta.persistence.GenerationType; | ||
| import jakarta.persistence.Id; | ||
| import jakarta.persistence.JoinColumn; | ||
| import jakarta.persistence.OneToMany; | ||
| import jakarta.persistence.Table; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Objects; | ||
|
|
||
| @Entity | ||
| @Table(name = "orders") | ||
| public class Order { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| @Column(name = "order_number") | ||
| private String orderNumber; | ||
|
|
||
| @OneToMany(fetch = FetchType.EAGER) | ||
| @JoinColumn(name = "order_id") | ||
| private List<OrderItem> orderItems; | ||
|
|
||
| public Order() { | ||
| } | ||
|
|
||
| public Order(Long id, String orderNumber, List<OrderItem> orderItems) { | ||
| this.id = id; | ||
| this.orderNumber = orderNumber; | ||
| this.orderItems = orderItems; | ||
| } | ||
|
|
||
| public Long getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public String getOrderNumber() { | ||
| return orderNumber; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object object) { | ||
| if (this == object) return true; | ||
| if (object == null || getClass() != object.getClass()) return false; | ||
| Order order = (Order) object; | ||
| return Objects.equals(id, order.id) && Objects.equals(orderNumber, order.orderNumber) && Objects.equals(orderItems, order.orderItems); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(id, orderNumber, orderItems); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Order{" + | ||
| "id=" + id + | ||
| ", orderNumber='" + orderNumber + '\'' + | ||
| ", orderItems=" + orderItems + | ||
| '}'; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| package entity; | ||
|
|
||
| import jakarta.persistence.Entity; | ||
| import jakarta.persistence.GeneratedValue; | ||
| import jakarta.persistence.GenerationType; | ||
| import jakarta.persistence.Id; | ||
| import jakarta.persistence.Table; | ||
|
|
||
| import java.util.Objects; | ||
|
|
||
| @Entity | ||
| @Table(name = "order_items") | ||
| public class OrderItem { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| private String product; | ||
|
|
||
| private Integer quantity; | ||
|
|
||
| public OrderItem() { | ||
| } | ||
|
|
||
| public OrderItem(Long id, String product, Integer quantity) { | ||
| this.id = id; | ||
| this.product = product; | ||
| this.quantity = quantity; | ||
| } | ||
|
|
||
| public Long getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public String getProduct() { | ||
| return product; | ||
| } | ||
|
|
||
| public Integer getQuantity() { | ||
| return quantity; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean equals(Object object) { | ||
| if (this == object) return true; | ||
| if (object == null || getClass() != object.getClass()) return false; | ||
| OrderItem orderItem = (OrderItem) object; | ||
| return Objects.equals(id, orderItem.id) && Objects.equals(product, orderItem.product) && Objects.equals(quantity, orderItem.quantity); | ||
| } | ||
|
|
||
| @Override | ||
| public int hashCode() { | ||
| return Objects.hash(id, product, quantity); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "OrderItem{" + | ||
| "id=" + id + | ||
| ", product='" + product + '\'' + | ||
| ", quantity=" + quantity + | ||
| '}'; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
72 changes: 72 additions & 0 deletions
72
src/main/java/persistence/sql/dml/CustomSelectQueryBuilder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| package persistence.sql.dml; | ||
|
|
||
| import pojo.EntityJoinMetaData; | ||
| import pojo.EntityMetaData; | ||
| import pojo.FieldInfos; | ||
| import pojo.IdField; | ||
|
|
||
| import java.lang.reflect.Field; | ||
| import java.lang.reflect.ParameterizedType; | ||
|
|
||
| import static constants.CommonConstants.COMMA; | ||
|
|
||
| public class CustomSelectQueryBuilder { | ||
|
|
||
| private static final String FIND_BY_ID_JOIN_QUERY = "SELECT %s FROM %s LEFT JOIN %s ON %s = %s WHERE %s = %s;"; | ||
|
|
||
| private final EntityJoinMetaData entityJoinMetaData; //Order | ||
| private final EntityMetaData owner; //OrderItem | ||
|
|
||
| public CustomSelectQueryBuilder(EntityJoinMetaData entityJoinMetaData) { | ||
| this.entityJoinMetaData = entityJoinMetaData; | ||
| this.owner = entityJoinMetaData.getOwner(); | ||
| } | ||
|
|
||
| public String findByIdJoinQuery1(Object entity, Class<?> clazz, Object condition) { | ||
| Field field = new FieldInfos(clazz.getDeclaredFields()).getIdField(); | ||
| IdField idField = new IdField(field, entity); | ||
|
|
||
| return String.format(FIND_BY_ID_JOIN_QUERY, getSelectData(), | ||
| entityJoinMetaData.getEntityName(), owner.getEntityName(), | ||
| entityJoinMetaData.getEntityName() + "." + idField.getFieldNameData(), | ||
| owner.getEntityName() + "." + entityJoinMetaData.joinColumnName(), | ||
| entityJoinMetaData.getEntityName() + "." + idField.getFieldNameData(), condition); | ||
| } | ||
|
|
||
| /** | ||
| * 아래 방법을 고민 중이라서 한번 피드백 부탁드립니다. | ||
| */ | ||
| public String findByIdJoinQuery2(Object entity, Class<?> clazz, Object condition) { | ||
| Field field = new FieldInfos(clazz.getDeclaredFields()).getIdField(); | ||
| IdField idField = new IdField(field, entity); | ||
|
|
||
| Field joinColumnField = new FieldInfos(clazz.getDeclaredFields()).getJoinColumnField(); | ||
| Class<?> subClass = (Class<?>) ((ParameterizedType) joinColumnField.getGenericType()).getActualTypeArguments()[0]; | ||
| EntityMetaData owner = new EntityMetaData(subClass, null); | ||
|
|
||
| return String.format(FIND_BY_ID_JOIN_QUERY, getSelectData(), | ||
| entityJoinMetaData.getEntityName(), owner.getEntityName(), | ||
| entityJoinMetaData.getEntityName() + "." + idField.getFieldNameData(), | ||
| owner.getEntityName() + "." + entityJoinMetaData.joinColumnName(), | ||
| entityJoinMetaData.getEntityName() + "." + idField.getFieldNameData(), condition); | ||
| } | ||
|
||
|
|
||
| private String getSelectData() { | ||
| String entityData = entityJoinMetaData.getEntityColumns() | ||
| .stream() | ||
| .map(entityColumn -> entityColumn.getFieldName().getName()) | ||
| .map(name -> entityJoinMetaData.getEntityName() + "." + name) | ||
| .reduce((o1, o2) -> String.join(COMMA, o1, o2)) | ||
| .orElseThrow(() -> new IllegalStateException("Id 혹은 Column 타입이 없습니다.")); | ||
|
|
||
| String ownerEntityData = owner.getEntityColumns() | ||
| .stream() | ||
| .map(entityColumn -> entityColumn.getFieldName().getName()) | ||
| .map(name -> owner.getEntityName() + "." + name) | ||
| .reduce((o1, o2) -> String.join(COMMA, o1, o2)) | ||
| .orElseThrow(() -> new IllegalStateException("Id 혹은 Column 타입이 없습니다.")); | ||
|
|
||
| return entityData + COMMA + ownerEntityData; | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
EntityJoinMeta를 생성 시 owner 의EntityMetaData(OrderItem) 를 먼저 생성해서 넣어주고, 그리고 연관관계를 가진 클래스(Order) 를 넣어주는 구조네요.현재의 구조는 몇가지 고려되지 않는 부분들이 존재하는데요! 그 중 가장 큰 문제는
EntityJoinMeta 생성을 자동화 할 수 없다는 점 같아요!
언제 어느 필드에 연관관계 어노테이션이 들어갈지 모르기에 수동으로 클래스를 넣어줘야하기 때문이죠
해당 부분을 해결하기위해
Field::getGenericType를 활용해서,EntityMetaData를 생성하는 시점에@OneToMany를 가진 필드의 클래스 정보를 가져오게끔 해서, 동적으로 연관관계 클래스를 가져오는 방식을 활용해보게끔 힌트가 주어진 것 같아요 :)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jongmin4943 종민님 이 부분은 처음에 어떻게 설계할지 고민을 했는데 위에서 피드백 주신 내용 중에 JoinColumn 에 대한 상태값을 가지는 책임을 EntityMetaData 에 넣어줌으로써 이 부분을 활용해볼 수 있을 것 같습니다. 감사합니다👍
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@jongmin4943 종민님 그런데 저 질문이 있는데요, 저는 저희 entity 클래스인 Order, OrderItem 만 고려한다고 할 때 여기서 EntityJoinMetaData 가 Order / EntityMetaData 가 OrderItem 이라고 보았어요. owner 를 OrderItem 으로 봐서 이렇게 설정을 했는데요~ 혹시 이런 상황이라면 두 클래스의 역할을 바꿔서 해야할까요? 아니면 EntityJoinMetaData, EntityMetaData 의 상위 인터페이스를 두고 추상화를 해야할지..? 이런 부분들이 좀 어려웠던 것 같습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
현재 구조에서 객체관계 주인은 누구를 뜻할까? 로 접근해보면 어떨까요?
개인적인 관점으로 얘기해드리자면, 현재
Order클래스가OrderItem을 가지고 있는 구조이니 owner 는Order가 되는 구조로 짜볼 것 같아요 😃저는 클래스명을 통한 추상화 레벨로 보았을때
EntityMetaData와EntityJoinMetaData는 같은 레벨로 보여서 상하위 체계를 갖는게 어색하다 느껴요! 두 클래스는 다른 책임을 가지고 있다고 생각해서, 현재구조에서 저라면, 각각을 생성할 것 같아요 :)