-
Notifications
You must be signed in to change notification settings - Fork 45
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
[Association - Step 1단계] OneToMany (FetchType.EAGER) #86
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 24 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 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 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 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 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 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 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 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 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 |
---|---|---|
|
@@ -19,5 +19,6 @@ public interface EntityEntry { | |
void postRemove(); | ||
|
||
void preReadOnly(); | ||
|
||
void postReadOnly(); | ||
} |
This file contains 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 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 |
---|---|---|
|
@@ -2,7 +2,9 @@ | |
|
||
import jdbc.JdbcTemplate; | ||
import jdbc.RowMapperImpl; | ||
import persistence.sql.dml.CustomSelectQueryBuilder; | ||
import persistence.sql.dml.SelectQueryBuilder; | ||
import pojo.EntityJoinMetaData; | ||
import pojo.EntityMetaData; | ||
|
||
import java.util.List; | ||
|
@@ -27,4 +29,24 @@ public <T> List<T> findAll(Class<T> clazz) { | |
SelectQueryBuilder selectQueryBuilder = new SelectQueryBuilder(entityMetaData); | ||
return jdbcTemplate.query(selectQueryBuilder.findAllQuery(), new RowMapperImpl<>(clazz)); | ||
} | ||
|
||
//연관관계가 있는 경우 & eager 타입만 고려 | ||
@Override | ||
public <T> List<T> findByIdWithAssociation(Class<T> clazz, Object entity, Object condition) { | ||
CustomSelectQueryBuilder customSelectQueryBuilder = new CustomSelectQueryBuilder(entityMetaData); | ||
|
||
EntityJoinMetaData entityJoinMetaData = entityMetaData.getEntityJoinMetaData(); | ||
if (!entityJoinMetaData.isLazy()) { | ||
return eagerTypeQuery(customSelectQueryBuilder, clazz, entity); | ||
} | ||
|
||
//TODO 추후 lazy 타입 넣을 예정 | ||
return jdbcTemplate.query(customSelectQueryBuilder.findByIdJoinQuery(entity, clazz), new RowMapperImpl<>(clazz)); | ||
|
||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 만드신 몇가지 생각해 볼만한 부분들이 있어요
|
||
|
||
private <T> List<T> eagerTypeQuery(CustomSelectQueryBuilder customSelectQueryBuilder, Class<T> clazz, Object entity) { | ||
return jdbcTemplate.query(customSelectQueryBuilder.findByIdJoinQuery(entity, clazz), new RowMapperImpl<>(clazz)); | ||
|
||
} | ||
} |
This file contains 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 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 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
57 changes: 57 additions & 0 deletions
57
src/main/java/persistence/sql/dml/CustomSelectQueryBuilder.java
This file contains 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,57 @@ | ||
package persistence.sql.dml; | ||
|
||
import pojo.EntityJoinMetaData; | ||
import pojo.EntityMetaData; | ||
import pojo.FieldInfos; | ||
import pojo.FieldName; | ||
import pojo.IdField; | ||
|
||
import java.lang.reflect.Field; | ||
|
||
import static constants.CommonConstants.COMMA; | ||
import static constants.CommonConstants.PERIOD; | ||
|
||
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 EntityMetaData entityMetaData; | ||
private final EntityJoinMetaData entityJoinMetaData; | ||
|
||
public CustomSelectQueryBuilder(EntityMetaData entityMetaData) { | ||
this.entityMetaData = entityMetaData; | ||
this.entityJoinMetaData = entityMetaData.getEntityJoinMetaData(); | ||
} | ||
|
||
public String findByIdJoinQuery(Object entity, Class<?> clazz) { | ||
Field field = new FieldInfos(clazz.getDeclaredFields()).getIdField(); | ||
IdField idField = new IdField(field, entity); | ||
|
||
String metaDataEntityName = entityMetaData.getEntityName(); | ||
String joinMetaDataEntityName = entityJoinMetaData.getEntityName(); | ||
|
||
return String.format(FIND_BY_ID_JOIN_QUERY, getSelectData(), metaDataEntityName, joinMetaDataEntityName, | ||
metaDataEntityName + PERIOD + idField.getFieldNameData(), | ||
joinMetaDataEntityName + PERIOD + entityJoinMetaData.getJoinColumnName(), | ||
metaDataEntityName + PERIOD + idField.getFieldNameData(), idField.getFieldValueData()); | ||
} | ||
|
||
private String getSelectData() { | ||
String entityData = entityMetaData.getEntityColumns() | ||
.stream() | ||
.map(entityColumn -> entityColumn.getFieldName().getName()) | ||
.map(name -> entityMetaData.getEntityName() + PERIOD + name) | ||
.reduce((o1, o2) -> String.join(COMMA, o1, o2)) | ||
.orElseThrow(() -> new IllegalStateException("Id 혹은 Column 타입이 없습니다.")); | ||
|
||
String ownerEntityData = entityJoinMetaData.getFieldNames() | ||
.stream() | ||
.map(FieldName::getName) | ||
.map(name -> entityJoinMetaData.getEntityName() + PERIOD + name) | ||
.reduce((o1, o2) -> String.join(COMMA, o1, o2)) | ||
.orElseThrow(() -> new IllegalStateException("Id 혹은 Column 타입이 없습니다.")); | ||
|
||
return entityData + COMMA + ownerEntityData; | ||
} | ||
|
||
} |
This file contains 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 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.
상수화 👍