From 99ee29b9cbf548daa10051cd47044b6e798efe16 Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Sat, 2 Nov 2024 18:27:40 +0900 Subject: [PATCH 1/9] =?UTF-8?q?refactor:=20=EC=BD=94=EB=93=9C=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. NsUser 참조 제거 2. 기수 수정 --- .../courses/Exception/ResponseType.java | 20 -------------- .../java/nextstep/courses/domain/Course.java | 10 +++---- .../nextstep/courses/domain/PricingType.java | 2 +- .../java/nextstep/courses/domain/Session.java | 7 +++-- .../nextstep/courses/domain/SessionDate.java | 2 +- .../domain/sessionimage/ImageCapacity.java | 2 +- .../domain/sessionimage/ImageSize.java | 2 +- .../domain/sessionimage/ImageType.java | 2 +- .../CustomException.java | 27 +++++++++---------- .../infrastructure/JdbcCourseRepository.java | 10 ++++--- .../nextstep/payments/domain/Payment.java | 10 +++---- src/main/resources/schema.sql | 1 + .../courses/domain/ImageCapacityTest.java | 4 +-- .../courses/domain/ImageSizeTest.java | 3 +-- .../courses/domain/ImageTypeTest.java | 3 +-- .../courses/domain/SessionDateTest.java | 2 +- .../nextstep/courses/domain/SessionTest.java | 8 +++--- 17 files changed, 45 insertions(+), 70 deletions(-) delete mode 100644 src/main/java/nextstep/courses/Exception/ResponseType.java rename src/main/java/nextstep/courses/{Exception => exception}/CustomException.java (52%) diff --git a/src/main/java/nextstep/courses/Exception/ResponseType.java b/src/main/java/nextstep/courses/Exception/ResponseType.java deleted file mode 100644 index 36a62529df..0000000000 --- a/src/main/java/nextstep/courses/Exception/ResponseType.java +++ /dev/null @@ -1,20 +0,0 @@ -package nextstep.courses.Exception; - -public enum ResponseType { - NOT_ALLOWED_DATE_MESSAGE("허용되지 않은 시작날짜입니다."), - OVER_MAX_IMAGE_CAPACITY("이미지 사이즈는 1MB 이하여야 합니다."), - IMAGE_SIZE_ERROR("이미지 사이즈 오류입니다."), - IMAGE_PERCENT_ERROR("이미지 비율 오류"), - NOT_ALLOWED_PREMIUM_AMOUNT("유료강의 금액은 0원이 될 수 없습니다."), - NOT_ALLOWED_FREE_AMOUNT("무료 강의 금액이 0원이 아닙니다."), - NOT_MACHING_SESSION_AMOUNT("강의 금액과 맞지 않습니다."), - MAX_STUDENTS_OVER("수강인원 초과"), - INVALID_SESSION_STATE("강의신청 기간이 아닙니다."), - INVALID_IMAGE_TYPE("이미지 타입이 올바르지 않습니다."); - - public String message; - - ResponseType(String message) { - this.message = message; - } -} diff --git a/src/main/java/nextstep/courses/domain/Course.java b/src/main/java/nextstep/courses/domain/Course.java index 911ba1112b..a533ec537a 100644 --- a/src/main/java/nextstep/courses/domain/Course.java +++ b/src/main/java/nextstep/courses/domain/Course.java @@ -14,23 +14,23 @@ public class Course { private Long creatorId; private LocalDateTime createdAt; private LocalDateTime updatedAt; - private List sessionList; + private List sessions; public Course() { } public Course(String title, Long creatorId) { - this(0L, title, creatorId, LocalDateTime.now(), null); + this(0L, title, creatorId, LocalDateTime.now(), null,1); } - public Course(Long id, String title, Long creatorId, LocalDateTime createdAt, LocalDateTime updatedAt) { + public Course(Long id, String title, Long creatorId, LocalDateTime createdAt, LocalDateTime updatedAt, int classNumber) { this.id = id; this.title = title; this.creatorId = creatorId; this.createdAt = createdAt; this.updatedAt = updatedAt; - sessionList = new ArrayList<>(); - classNumber = count.incrementAndGet(); + sessions = new ArrayList<>(); + this.classNumber = classNumber; } public String getTitle() { diff --git a/src/main/java/nextstep/courses/domain/PricingType.java b/src/main/java/nextstep/courses/domain/PricingType.java index e0d5512c70..774a4bf7b8 100644 --- a/src/main/java/nextstep/courses/domain/PricingType.java +++ b/src/main/java/nextstep/courses/domain/PricingType.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.payments.domain.Payment; public class PricingType { diff --git a/src/main/java/nextstep/courses/domain/Session.java b/src/main/java/nextstep/courses/domain/Session.java index 0fdab2818e..1731f2008b 100644 --- a/src/main/java/nextstep/courses/domain/Session.java +++ b/src/main/java/nextstep/courses/domain/Session.java @@ -1,15 +1,14 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.courses.domain.sessionimage.SessionImage; import nextstep.payments.domain.Payment; -import nextstep.users.domain.NsUser; import java.util.ArrayList; import java.util.List; public class Session { - private List students; + private List students; private PricingType pricingType; private SessionState state; private SessionImage image; @@ -19,7 +18,7 @@ public class Session { public Session(PricingType pricingType, int maxStudentCount, SessionState state, SessionDate date , SessionImage image) { this.pricingType = pricingType; - this.students = new ArrayList<>(); + this.students = new ArrayList(); this.maxStudentCount = maxStudentCount; this.state = state; this.date = date; diff --git a/src/main/java/nextstep/courses/domain/SessionDate.java b/src/main/java/nextstep/courses/domain/SessionDate.java index ec55634350..3ea7641ac8 100644 --- a/src/main/java/nextstep/courses/domain/SessionDate.java +++ b/src/main/java/nextstep/courses/domain/SessionDate.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import java.time.LocalDateTime; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java b/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java index 61b7857699..465adf6853 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java +++ b/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java @@ -1,6 +1,6 @@ package nextstep.courses.domain.sessionimage; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; public class ImageCapacity { diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java b/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java index c361b9e1b0..6dd2e2d855 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java +++ b/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java @@ -1,6 +1,6 @@ package nextstep.courses.domain.sessionimage; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import java.math.BigDecimal; import java.math.RoundingMode; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java b/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java index 17f5371374..ebae1dfa8c 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java +++ b/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java @@ -1,6 +1,6 @@ package nextstep.courses.domain.sessionimage; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import java.util.Arrays; diff --git a/src/main/java/nextstep/courses/Exception/CustomException.java b/src/main/java/nextstep/courses/exception/CustomException.java similarity index 52% rename from src/main/java/nextstep/courses/Exception/CustomException.java rename to src/main/java/nextstep/courses/exception/CustomException.java index 61a5f99aed..55cf73a2a9 100644 --- a/src/main/java/nextstep/courses/Exception/CustomException.java +++ b/src/main/java/nextstep/courses/exception/CustomException.java @@ -1,20 +1,20 @@ -package nextstep.courses.Exception; +package nextstep.courses.exception; public class CustomException extends RuntimeException { - public static final CustomException NOT_ALLOWED_DATE = new CustomException(ResponseType.NOT_ALLOWED_DATE_MESSAGE); - public static final CustomException OVER_MAX_IMAGE_CAPACITY = new CustomException(ResponseType.OVER_MAX_IMAGE_CAPACITY); - public static final CustomException IMAGE_SIZE_ERROR = new CustomException(ResponseType.IMAGE_SIZE_ERROR); - public static final CustomException IMAGE_PERCENT_ERROR = new CustomException(ResponseType.IMAGE_PERCENT_ERROR); - public static final CustomException NOT_ALLOWED_PREMIUM_AMOUNT = new CustomException(ResponseType.NOT_ALLOWED_PREMIUM_AMOUNT); - public static final CustomException NOT_ALLOWED_FREE_AMOUNT = new CustomException(ResponseType.NOT_ALLOWED_FREE_AMOUNT); - public static final CustomException NOT_MATCHING_SESSION_AMOUNT = new CustomException(ResponseType.NOT_MACHING_SESSION_AMOUNT); - public static final CustomException MAX_STUDENTS_OVER = new CustomException(ResponseType.MAX_STUDENTS_OVER); - public static final CustomException INVALID_SESSION_STATE = new CustomException(ResponseType.INVALID_SESSION_STATE); - public static final CustomException INVALID_IMAGE_TYPE = new CustomException(ResponseType.INVALID_IMAGE_TYPE); + public static final CustomException NOT_ALLOWED_DATE = new CustomException("허용되지 않은 시작날짜입니다."); + public static final CustomException OVER_MAX_IMAGE_CAPACITY = new CustomException("이미지 사이즈는 1MB 이하여야 합니다."); + public static final CustomException IMAGE_SIZE_ERROR = new CustomException("이미지 사이즈 오류입니다."); + public static final CustomException IMAGE_PERCENT_ERROR = new CustomException("이미지 비율 오류"); + public static final CustomException NOT_ALLOWED_PREMIUM_AMOUNT = new CustomException("유료강의 금액은 0원이 될 수 없습니다."); + public static final CustomException NOT_ALLOWED_FREE_AMOUNT = new CustomException("무료 강의 금액이 0원이 아닙니다."); + public static final CustomException NOT_MATCHING_SESSION_AMOUNT = new CustomException("강의 금액과 맞지 않습니다."); + public static final CustomException MAX_STUDENTS_OVER = new CustomException("수강인원 초과"); + public static final CustomException INVALID_SESSION_STATE = new CustomException("강의신청 기간이 아닙니다."); + public static final CustomException INVALID_IMAGE_TYPE = new CustomException("이미지 타입이 올바르지 않습니다."); - public CustomException(ResponseType responseType) { - super(responseType.message); + public CustomException(String message) { + super(message); } @Override @@ -22,5 +22,4 @@ public synchronized Throwable fillInStackTrace() { return this; } - } diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java index f9122cbe33..20151d2cac 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java @@ -19,19 +19,21 @@ public JdbcCourseRepository(JdbcOperations jdbcTemplate) { @Override public int save(Course course) { - String sql = "insert into course (title, creator_id, created_at) values(?, ?, ?)"; - return jdbcTemplate.update(sql, course.getTitle(), course.getCreatorId(), course.getCreatedAt()); + String sql = "insert into course (title, creator_id, created_at, class_number) values(?, ?, ?,?)"; + return jdbcTemplate.update(sql, course.getTitle(), course.getCreatorId(), course.getCreatedAt(),1); } @Override public Course findById(Long id) { - String sql = "select id, title, creator_id, created_at, updated_at from course where id = ?"; + String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = ?"; RowMapper rowMapper = (rs, rowNum) -> new Course( rs.getLong(1), rs.getString(2), rs.getLong(3), toLocalDateTime(rs.getTimestamp(4)), - toLocalDateTime(rs.getTimestamp(5))); + toLocalDateTime(rs.getTimestamp(5)), + rs.getInt(6) + ); return jdbcTemplate.queryForObject(sql, rowMapper, id); } diff --git a/src/main/java/nextstep/payments/domain/Payment.java b/src/main/java/nextstep/payments/domain/Payment.java index efde967573..6ff7a3136a 100644 --- a/src/main/java/nextstep/payments/domain/Payment.java +++ b/src/main/java/nextstep/payments/domain/Payment.java @@ -11,7 +11,7 @@ public class Payment { private Long sessionId; // 결제한 사용자 아이디 - private NsUser nsUser; + private Long nsUserId; // 결제 금액 private Long amount; @@ -21,16 +21,16 @@ public class Payment { public Payment() { } - public Payment(String id, Long sessionId, NsUser nsUser, Long amount) { + public Payment(String id, Long sessionId, Long nsUserId, Long amount) { this.id = id; this.sessionId = sessionId; - this.nsUser = nsUser; + this.nsUserId = nsUserId; this.amount = amount; this.createdAt = LocalDateTime.now(); } - public NsUser payingUser() { - return nsUser; + public Long payingUser() { + return nsUserId; } public boolean matchingAmount(int sessionAmount) { diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index 8d5a988c8b..eeacdda01f 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -4,6 +4,7 @@ create table course ( creator_id bigint not null, created_at timestamp not null, updated_at timestamp, + class_number bigint not null, primary key (id) ); diff --git a/src/test/java/nextstep/courses/domain/ImageCapacityTest.java b/src/test/java/nextstep/courses/domain/ImageCapacityTest.java index 6970ed4680..7775772003 100644 --- a/src/test/java/nextstep/courses/domain/ImageCapacityTest.java +++ b/src/test/java/nextstep/courses/domain/ImageCapacityTest.java @@ -1,16 +1,14 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.courses.domain.sessionimage.ImageCapacity; import nextstep.courses.domain.sessionimage.ImageSize; import nextstep.courses.domain.sessionimage.ImageType; import nextstep.courses.domain.sessionimage.SessionImage; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; diff --git a/src/test/java/nextstep/courses/domain/ImageSizeTest.java b/src/test/java/nextstep/courses/domain/ImageSizeTest.java index 988f55fc81..9fc399111a 100644 --- a/src/test/java/nextstep/courses/domain/ImageSizeTest.java +++ b/src/test/java/nextstep/courses/domain/ImageSizeTest.java @@ -1,11 +1,10 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.courses.domain.sessionimage.ImageSize; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ImageSizeTest { diff --git a/src/test/java/nextstep/courses/domain/ImageTypeTest.java b/src/test/java/nextstep/courses/domain/ImageTypeTest.java index b97de82ec0..b5aa44b523 100644 --- a/src/test/java/nextstep/courses/domain/ImageTypeTest.java +++ b/src/test/java/nextstep/courses/domain/ImageTypeTest.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.courses.domain.sessionimage.ImageCapacity; import nextstep.courses.domain.sessionimage.ImageSize; import nextstep.courses.domain.sessionimage.ImageType; @@ -8,7 +8,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; diff --git a/src/test/java/nextstep/courses/domain/SessionDateTest.java b/src/test/java/nextstep/courses/domain/SessionDateTest.java index 0e503ac3a8..bc230620ef 100644 --- a/src/test/java/nextstep/courses/domain/SessionDateTest.java +++ b/src/test/java/nextstep/courses/domain/SessionDateTest.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; diff --git a/src/test/java/nextstep/courses/domain/SessionTest.java b/src/test/java/nextstep/courses/domain/SessionTest.java index 885edbd8f0..16bed115a1 100644 --- a/src/test/java/nextstep/courses/domain/SessionTest.java +++ b/src/test/java/nextstep/courses/domain/SessionTest.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; -import nextstep.courses.Exception.CustomException; +import nextstep.courses.exception.CustomException; import nextstep.courses.domain.sessionimage.ImageCapacity; import nextstep.courses.domain.sessionimage.ImageSize; import nextstep.courses.domain.sessionimage.ImageType; @@ -12,7 +12,6 @@ import java.time.LocalDateTime; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -34,9 +33,8 @@ public class SessionTest { public void setUp() { sessionDate = new SessionDate(LocalDateTime.now(), LocalDateTime.now().plusDays(2)); - NsUser nsUser = new NsUser(1L, "test", "pwd", "wonsuk", "email"); - matchPayment = new Payment("test", 1L, nsUser, 10000L); - unMatchPayment = new Payment("test", 1L, nsUser, 9000L); + matchPayment = new Payment("test", 1L, 1L, 10000L); + unMatchPayment = new Payment("test", 1L, 1L, 9000L); imageCapacity = new ImageCapacity(IMAGE_CAPACITY); imageSize = new ImageSize(WIDTH, HEIGHT); From b3f2ee96c9fbb1e373cc3e8a7b9701aabb1ed7cb Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Sun, 3 Nov 2024 21:46:21 +0900 Subject: [PATCH 2/9] =?UTF-8?q?chore:=20=ED=8C=A8=ED=82=A4=EC=A7=80?= =?UTF-8?q?=EB=AA=85=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- STEP3README.md | 41 +++++++++++++++++++ .../java/nextstep/courses/domain/Session.java | 2 +- .../ImageCapacity.java | 2 +- .../{sessionimage => image}/ImageSize.java | 2 +- .../{sessionimage => image}/ImageType.java | 2 +- .../{sessionimage => image}/SessionImage.java | 2 +- .../courses/domain/ImageCapacityTest.java | 8 ++-- .../courses/domain/ImageSizeTest.java | 2 +- .../courses/domain/ImageTypeTest.java | 8 ++-- .../nextstep/courses/domain/SessionTest.java | 9 ++-- 10 files changed, 59 insertions(+), 19 deletions(-) create mode 100644 STEP3README.md rename src/main/java/nextstep/courses/domain/{sessionimage => image}/ImageCapacity.java (92%) rename src/main/java/nextstep/courses/domain/{sessionimage => image}/ImageSize.java (95%) rename src/main/java/nextstep/courses/domain/{sessionimage => image}/ImageType.java (89%) rename src/main/java/nextstep/courses/domain/{sessionimage => image}/SessionImage.java (88%) diff --git a/STEP3README.md b/STEP3README.md new file mode 100644 index 0000000000..fef380fdbb --- /dev/null +++ b/STEP3README.md @@ -0,0 +1,41 @@ +# 학습 관리 시스템(Learning Management System) + +## step3 요구사항 + +1. [ ] 앞단계에서 구현한 도메인 모델 DB와 매핑하고 데이터 저장 +2. + 2. 테이블 설계하고 객체매핑 +2. [ ] Payments는 테이블 매핑 미고려 + +## 관련 클래스 + +1. DB 테이블 resources/schema.sql +2. jdbcCourseRepository +3. CourseRepositoryTest + + + +## 테스트 필요 내용 + +-이미지 크기는 1MB이하. +-이미지 크기 1MB 초과 및 0이하 실패 +-이미지타입 일치 불일치 테스트 +-이미지 사이즈 테스트 + +- 무료강의 무제한 인원 테스트 + +## 피드백 + +1. 패키지명 소문자 컨벤션 +2. 클래스 내부 상수,변수와 메서드 개행으로 구분 +3. 생성 검증테스트시 불필요한 변수할당 제외하기 +4. 단위테스트간 독립성 유지하기. 테스트간 서로 영향을 주면 테스트가 어렵다. +5. 한줄이상 불필요 개행 제거 +6. 오해나 혼동을 줄 수 있는 클래스명이나 변수명 개선 +7. 맹목적인 일급컬렉션 사용대신, 의도에 맞게 사용하기.(ex: 일급컬렉션생성시 컬렉션만의 로직이 존재하면 래핑할 가치가 있음) +8. 커스텀 exception. 예외성성의 비용이 비싸다. 스택의 depth에 따라 10이면 4000나노초. 오버라이딩하면 80나노초. + 9. + 1. 커스텀 Exception 클래스에서 fillInStackTrace trace안하도록 오버라이딩하기 -> 커스텀Exception은 비즈니스로직 실패 방지용도이므로 call stack에 대한 + trace는 불필요하므로 + 10. static final로 exception들 new로 미리 생성. + 11. 핸들링이 필요한 영역에서 호출. \ No newline at end of file diff --git a/src/main/java/nextstep/courses/domain/Session.java b/src/main/java/nextstep/courses/domain/Session.java index 1731f2008b..53989e09d7 100644 --- a/src/main/java/nextstep/courses/domain/Session.java +++ b/src/main/java/nextstep/courses/domain/Session.java @@ -1,7 +1,7 @@ package nextstep.courses.domain; import nextstep.courses.exception.CustomException; -import nextstep.courses.domain.sessionimage.SessionImage; +import nextstep.courses.domain.image.SessionImage; import nextstep.payments.domain.Payment; import java.util.ArrayList; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java b/src/main/java/nextstep/courses/domain/image/ImageCapacity.java similarity index 92% rename from src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java rename to src/main/java/nextstep/courses/domain/image/ImageCapacity.java index 465adf6853..8ac29e8f44 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageCapacity.java +++ b/src/main/java/nextstep/courses/domain/image/ImageCapacity.java @@ -1,4 +1,4 @@ -package nextstep.courses.domain.sessionimage; +package nextstep.courses.domain.image; import nextstep.courses.exception.CustomException; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java b/src/main/java/nextstep/courses/domain/image/ImageSize.java similarity index 95% rename from src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java rename to src/main/java/nextstep/courses/domain/image/ImageSize.java index 6dd2e2d855..59336c009c 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageSize.java +++ b/src/main/java/nextstep/courses/domain/image/ImageSize.java @@ -1,4 +1,4 @@ -package nextstep.courses.domain.sessionimage; +package nextstep.courses.domain.image; import nextstep.courses.exception.CustomException; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java b/src/main/java/nextstep/courses/domain/image/ImageType.java similarity index 89% rename from src/main/java/nextstep/courses/domain/sessionimage/ImageType.java rename to src/main/java/nextstep/courses/domain/image/ImageType.java index ebae1dfa8c..c084fa97e3 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/ImageType.java +++ b/src/main/java/nextstep/courses/domain/image/ImageType.java @@ -1,4 +1,4 @@ -package nextstep.courses.domain.sessionimage; +package nextstep.courses.domain.image; import nextstep.courses.exception.CustomException; diff --git a/src/main/java/nextstep/courses/domain/sessionimage/SessionImage.java b/src/main/java/nextstep/courses/domain/image/SessionImage.java similarity index 88% rename from src/main/java/nextstep/courses/domain/sessionimage/SessionImage.java rename to src/main/java/nextstep/courses/domain/image/SessionImage.java index 793d110a2a..b62745e1d5 100644 --- a/src/main/java/nextstep/courses/domain/sessionimage/SessionImage.java +++ b/src/main/java/nextstep/courses/domain/image/SessionImage.java @@ -1,4 +1,4 @@ -package nextstep.courses.domain.sessionimage; +package nextstep.courses.domain.image; public class SessionImage { diff --git a/src/test/java/nextstep/courses/domain/ImageCapacityTest.java b/src/test/java/nextstep/courses/domain/ImageCapacityTest.java index 7775772003..596a8eff32 100644 --- a/src/test/java/nextstep/courses/domain/ImageCapacityTest.java +++ b/src/test/java/nextstep/courses/domain/ImageCapacityTest.java @@ -1,10 +1,10 @@ package nextstep.courses.domain; import nextstep.courses.exception.CustomException; -import nextstep.courses.domain.sessionimage.ImageCapacity; -import nextstep.courses.domain.sessionimage.ImageSize; -import nextstep.courses.domain.sessionimage.ImageType; -import nextstep.courses.domain.sessionimage.SessionImage; +import nextstep.courses.domain.image.ImageCapacity; +import nextstep.courses.domain.image.ImageSize; +import nextstep.courses.domain.image.ImageType; +import nextstep.courses.domain.image.SessionImage; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/src/test/java/nextstep/courses/domain/ImageSizeTest.java b/src/test/java/nextstep/courses/domain/ImageSizeTest.java index 9fc399111a..2efbab02fb 100644 --- a/src/test/java/nextstep/courses/domain/ImageSizeTest.java +++ b/src/test/java/nextstep/courses/domain/ImageSizeTest.java @@ -1,7 +1,7 @@ package nextstep.courses.domain; import nextstep.courses.exception.CustomException; -import nextstep.courses.domain.sessionimage.ImageSize; +import nextstep.courses.domain.image.ImageSize; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; diff --git a/src/test/java/nextstep/courses/domain/ImageTypeTest.java b/src/test/java/nextstep/courses/domain/ImageTypeTest.java index b5aa44b523..e4417b0ac0 100644 --- a/src/test/java/nextstep/courses/domain/ImageTypeTest.java +++ b/src/test/java/nextstep/courses/domain/ImageTypeTest.java @@ -1,10 +1,10 @@ package nextstep.courses.domain; import nextstep.courses.exception.CustomException; -import nextstep.courses.domain.sessionimage.ImageCapacity; -import nextstep.courses.domain.sessionimage.ImageSize; -import nextstep.courses.domain.sessionimage.ImageType; -import nextstep.courses.domain.sessionimage.SessionImage; +import nextstep.courses.domain.image.ImageCapacity; +import nextstep.courses.domain.image.ImageSize; +import nextstep.courses.domain.image.ImageType; +import nextstep.courses.domain.image.SessionImage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/nextstep/courses/domain/SessionTest.java b/src/test/java/nextstep/courses/domain/SessionTest.java index 16bed115a1..67adf97577 100644 --- a/src/test/java/nextstep/courses/domain/SessionTest.java +++ b/src/test/java/nextstep/courses/domain/SessionTest.java @@ -1,12 +1,11 @@ package nextstep.courses.domain; import nextstep.courses.exception.CustomException; -import nextstep.courses.domain.sessionimage.ImageCapacity; -import nextstep.courses.domain.sessionimage.ImageSize; -import nextstep.courses.domain.sessionimage.ImageType; -import nextstep.courses.domain.sessionimage.SessionImage; +import nextstep.courses.domain.image.ImageCapacity; +import nextstep.courses.domain.image.ImageSize; +import nextstep.courses.domain.image.ImageType; +import nextstep.courses.domain.image.SessionImage; import nextstep.payments.domain.Payment; -import nextstep.users.domain.NsUser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; From 9b3eae7c7e7068302243bbf7c30158ff61ca908a Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Tue, 5 Nov 2024 00:28:10 +0900 Subject: [PATCH 3/9] =?UTF-8?q?feat:=20sql=EB=AC=B8=20=EC=9E=91=EC=84=B1?= =?UTF-8?q?=20=EC=A7=84=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../courses/domain/SessionRepository.java | 6 +++++ .../courses/domain/image/ImageType.java | 1 - src/main/resources/schema.sql | 23 +++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 src/main/java/nextstep/courses/domain/SessionRepository.java diff --git a/src/main/java/nextstep/courses/domain/SessionRepository.java b/src/main/java/nextstep/courses/domain/SessionRepository.java new file mode 100644 index 0000000000..73ac1dc5e0 --- /dev/null +++ b/src/main/java/nextstep/courses/domain/SessionRepository.java @@ -0,0 +1,6 @@ +package nextstep.courses.domain; + +public interface SessionRepository { + int save(Session session); + Session findById(Long id); +} diff --git a/src/main/java/nextstep/courses/domain/image/ImageType.java b/src/main/java/nextstep/courses/domain/image/ImageType.java index c084fa97e3..bf8db48ece 100644 --- a/src/main/java/nextstep/courses/domain/image/ImageType.java +++ b/src/main/java/nextstep/courses/domain/image/ImageType.java @@ -12,7 +12,6 @@ public enum ImageType { png, svg; - public static ImageType validateType(String imageType) { return Arrays.stream(values()).filter(type -> type.name().equals(imageType)) .findFirst() diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index eeacdda01f..cfd65a4499 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -8,6 +8,29 @@ create table course ( primary key (id) ); +create table session ( + id bigint generated by default as identity, + session_amount int not null, + is_premium boolean not null, + session_state varchar not null, + image_capacity int, + image_type varchar, + image_width int, + image_height int, + max_student_count int, + start_date timestamp, + end_date timestamp, + primary key (id) +); + +create table session_students ( + id bigint generated by default as identity, + session_id bigint, + primary key (id) + foreign key (session_id) REFERENCES SESSION(id) +); + + create table ns_user ( id bigint generated by default as identity, user_id varchar(20) not null, From cdd9531e9801a5aec32199b1287325be08e4a3d8 Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Wed, 6 Nov 2024 00:36:55 +0900 Subject: [PATCH 4/9] =?UTF-8?q?feat:=20sql=EB=AC=B8=20=EB=A7=A4=ED=95=91?= =?UTF-8?q?=20=EB=B0=8F=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../nextstep/courses/domain/PricingType.java | 12 +- .../java/nextstep/courses/domain/Session.java | 46 ++++++- .../nextstep/courses/domain/SessionDate.java | 8 ++ .../courses/domain/SessionRepository.java | 2 +- .../nextstep/courses/domain/SessionState.java | 3 + .../courses/domain/image/ImageCapacity.java | 6 + .../courses/domain/image/ImageSize.java | 9 ++ .../courses/domain/image/SessionImage.java | 14 ++- .../infrastructure/JdbcSessionRepository.java | 119 ++++++++++++++++++ src/main/resources/schema.sql | 7 +- .../infrastructure/SessionRepositoryTest.java | 53 ++++++++ 11 files changed, 270 insertions(+), 9 deletions(-) create mode 100644 src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java create mode 100644 src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java diff --git a/src/main/java/nextstep/courses/domain/PricingType.java b/src/main/java/nextstep/courses/domain/PricingType.java index 774a4bf7b8..e1c27b804e 100644 --- a/src/main/java/nextstep/courses/domain/PricingType.java +++ b/src/main/java/nextstep/courses/domain/PricingType.java @@ -6,7 +6,9 @@ public class PricingType { private final int sessionAmount; - private boolean isPremium; + private final boolean isPremium; + + public PricingType(boolean isPremium, int sessionAmount) { validate(isPremium,sessionAmount); @@ -32,4 +34,12 @@ public void validateAmount(Payment payment) { throw CustomException.NOT_MATCHING_SESSION_AMOUNT; } } + + public int getSessionAmount() { + return sessionAmount; + } + + public boolean getIsPremium() { + return isPremium; + } } diff --git a/src/main/java/nextstep/courses/domain/Session.java b/src/main/java/nextstep/courses/domain/Session.java index 53989e09d7..f97238abcf 100644 --- a/src/main/java/nextstep/courses/domain/Session.java +++ b/src/main/java/nextstep/courses/domain/Session.java @@ -8,6 +8,7 @@ import java.util.List; public class Session { + private Long id; private List students; private PricingType pricingType; private SessionState state; @@ -15,15 +16,30 @@ public class Session { private int maxStudentCount; private SessionDate date; + public Session(PricingType pricingType, int maxStudentCount, SessionState state, SessionDate date , SessionImage image) { + this(0L, new ArrayList(),pricingType,state,image,maxStudentCount,date); + } + + public Session(List students, PricingType pricingType, SessionState state, SessionImage image, int maxStudentCount, SessionDate date) { + this.id = 0L; + this.students = students; this.pricingType = pricingType; - this.students = new ArrayList(); - this.maxStudentCount = maxStudentCount; this.state = state; - this.date = date; this.image = image; + this.maxStudentCount = maxStudentCount; + this.date = date; + } + public Session(Long id, List students, PricingType pricingType, SessionState state, SessionImage image, int maxStudentCount, SessionDate date) { + this.id = id; + this.students = students; + this.pricingType = pricingType; + this.state = state; + this.image = image; + this.maxStudentCount = maxStudentCount; + this.date = date; } public void requestSession(Payment payment) { @@ -46,4 +62,28 @@ private void validateSessionState() { } + public List getStudents() { + return students; + } + + public PricingType getPricingType() { + return pricingType; + } + + public SessionState getState() { + return state; + } + + public SessionImage getImage() { + return image; + } + + public int getMaxStudentCount() { + return maxStudentCount; + } + + public SessionDate getDate() { + return date; + } + } diff --git a/src/main/java/nextstep/courses/domain/SessionDate.java b/src/main/java/nextstep/courses/domain/SessionDate.java index 3ea7641ac8..86ebe42fbe 100644 --- a/src/main/java/nextstep/courses/domain/SessionDate.java +++ b/src/main/java/nextstep/courses/domain/SessionDate.java @@ -15,4 +15,12 @@ public SessionDate(LocalDateTime startDate, LocalDateTime endDate) { this.startDate = startDate; this.endDate = endDate; } + + public LocalDateTime getStartDate() { + return startDate; + } + + public LocalDateTime getEndDate() { + return endDate; + } } diff --git a/src/main/java/nextstep/courses/domain/SessionRepository.java b/src/main/java/nextstep/courses/domain/SessionRepository.java index 73ac1dc5e0..9c9648bee3 100644 --- a/src/main/java/nextstep/courses/domain/SessionRepository.java +++ b/src/main/java/nextstep/courses/domain/SessionRepository.java @@ -1,6 +1,6 @@ package nextstep.courses.domain; public interface SessionRepository { - int save(Session session); + long save(Session session); Session findById(Long id); } diff --git a/src/main/java/nextstep/courses/domain/SessionState.java b/src/main/java/nextstep/courses/domain/SessionState.java index 24ab0e03d1..5210cd55e6 100644 --- a/src/main/java/nextstep/courses/domain/SessionState.java +++ b/src/main/java/nextstep/courses/domain/SessionState.java @@ -3,6 +3,9 @@ public enum SessionState { READY("READY"), START("START"), END("END"); + public String getState() { + return state; + } public String state; diff --git a/src/main/java/nextstep/courses/domain/image/ImageCapacity.java b/src/main/java/nextstep/courses/domain/image/ImageCapacity.java index 8ac29e8f44..5375a78cc5 100644 --- a/src/main/java/nextstep/courses/domain/image/ImageCapacity.java +++ b/src/main/java/nextstep/courses/domain/image/ImageCapacity.java @@ -9,6 +9,7 @@ public class ImageCapacity { private final int imageSize; + public ImageCapacity(int imageSize) { validateSize(imageSize); this.imageSize = imageSize; @@ -19,4 +20,9 @@ private void validateSize(int imageSize) { throw CustomException.OVER_MAX_IMAGE_CAPACITY; } } + + public int getImageSize() { + return imageSize; + } + } diff --git a/src/main/java/nextstep/courses/domain/image/ImageSize.java b/src/main/java/nextstep/courses/domain/image/ImageSize.java index 59336c009c..55529f74e1 100644 --- a/src/main/java/nextstep/courses/domain/image/ImageSize.java +++ b/src/main/java/nextstep/courses/domain/image/ImageSize.java @@ -29,4 +29,13 @@ private void validateSize(int width, int height) { throw CustomException.IMAGE_PERCENT_ERROR; } } + + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } } diff --git a/src/main/java/nextstep/courses/domain/image/SessionImage.java b/src/main/java/nextstep/courses/domain/image/SessionImage.java index b62745e1d5..7358f4ca51 100644 --- a/src/main/java/nextstep/courses/domain/image/SessionImage.java +++ b/src/main/java/nextstep/courses/domain/image/SessionImage.java @@ -6,11 +6,23 @@ public class SessionImage { private final ImageType type; private final ImageSize size; - public SessionImage(ImageCapacity capacity, ImageType type, ImageSize size) { ImageType.validateType(type.name()); this.capacity = capacity; this.type = type; this.size = size; } + + public ImageCapacity getCapacity() { + return capacity; + } + + public ImageType getType() { + return type; + } + + public ImageSize getSize() { + return size; + } + } diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java new file mode 100644 index 0000000000..b7ebb77aac --- /dev/null +++ b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java @@ -0,0 +1,119 @@ +package nextstep.courses.infrastructure; + +import nextstep.courses.domain.*; +import nextstep.courses.domain.image.ImageCapacity; +import nextstep.courses.domain.image.ImageSize; +import nextstep.courses.domain.image.ImageType; +import nextstep.courses.domain.image.SessionImage; +import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; +import org.springframework.stereotype.Repository; + +import java.sql.PreparedStatement; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Repository("sessionRepository") +public class JdbcSessionRepository implements SessionRepository { + private JdbcOperations jdbcTemplate; + + public JdbcSessionRepository(JdbcOperations jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public long save(Session session) { + String sql = "insert into session (session_amount," + + " is_premium," + + " session_state," + + " image_capacity,image_type, image_width, image_height, max_student_count," + + "start_date, end_date" + + ") values(?,?,?,?,?,?,?,?,?,?)"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + jdbcTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"}); + ps.setInt(1, session.getPricingType().getSessionAmount()); + ps.setBoolean(2, session.getPricingType().getIsPremium()); + ps.setString(3, session.getState().getState()); + ps.setInt(4, session.getImage().getCapacity().getImageSize()); + ps.setString(5, session.getImage().getType().toString()); + ps.setInt(6, session.getImage().getSize().getWidth()); + ps.setInt(7, session.getImage().getSize().getHeight()); + ps.setInt(8, session.getMaxStudentCount()); + ps.setTimestamp(9, Timestamp.valueOf(session.getDate().getStartDate())); + ps.setTimestamp(10, Timestamp.valueOf(session.getDate().getEndDate())); + return ps; + }, keyHolder); + + long pk = keyHolder.getKey().longValue(); + + for (Long studentId : session.getStudents()) { + saveSessionStudent(pk, studentId); + } + return pk; + } + + private long saveSessionStudent(long pk, Long studentId) { + + String sql = "insert into session_students (id, session_id" + + ") values(?,?);"; + KeyHolder keyHolder = new GeneratedKeyHolder(); + + jdbcTemplate.update(connection -> { + PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"}); + ps.setLong(1, studentId); + ps.setLong(2, pk); + return ps; + }, keyHolder); + + return keyHolder.getKey().longValue(); + } + + @Override + public Session findById(Long id) { + String sql = "select id," + + " session_amount," + + " is_premium," + + " session_state," + + " image_capacity," + + " image_type," + + " image_width, image_height, max_student_count, start_date, end_date from session where id = ?"; + RowMapper rowMapper = (rs, rowNum) -> { + long pk = rs.getLong(1); + List students = findStudents(pk); + + return new Session(pk, + students, + new PricingType( rs.getBoolean(3), rs.getInt(2)), + SessionState.valueOf(rs.getString(4)), + new SessionImage(new ImageCapacity(rs.getInt(5)), ImageType.valueOf(rs.getString(6)), new ImageSize(rs.getInt(7),rs.getInt(8))), + rs.getInt(9), + new SessionDate(toLocalDateTime(rs.getTimestamp(10)), toLocalDateTime(rs.getTimestamp(11)))); + }; + + return jdbcTemplate.queryForObject(sql, rowMapper, id); + } + + private List findStudents(long pk) { + String sql = "select id from session_students where session_id = ?"; + return jdbcTemplate.query(sql, rs -> { + List studentIdList = new ArrayList<>(); + while (rs.next()) { + studentIdList.add(rs.getLong(1)); + } + return studentIdList; + }, pk); + } + + private LocalDateTime toLocalDateTime(Timestamp timestamp) { + if (timestamp == null) { + return null; + } + return timestamp.toLocalDateTime(); + } +} diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index cfd65a4499..ddcb49ef8e 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -24,10 +24,11 @@ create table session ( ); create table session_students ( - id bigint generated by default as identity, + id bigint not null, session_id bigint, - primary key (id) - foreign key (session_id) REFERENCES SESSION(id) + primary key (id), + foreign key (session_id) REFERENCES SESSION(id), + constraint unique_registration unique (id, session_id) ); diff --git a/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java b/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java new file mode 100644 index 0000000000..cd706724a7 --- /dev/null +++ b/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java @@ -0,0 +1,53 @@ +package nextstep.courses.infrastructure; + +import nextstep.courses.domain.*; +import nextstep.courses.domain.image.ImageCapacity; +import nextstep.courses.domain.image.ImageSize; +import nextstep.courses.domain.image.ImageType; +import nextstep.courses.domain.image.SessionImage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; +import org.springframework.jdbc.core.JdbcTemplate; + +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@JdbcTest +public class SessionRepositoryTest { + private static final Logger LOGGER = LoggerFactory.getLogger(SessionRepositoryTest.class); + + @Autowired + private JdbcTemplate jdbcTemplate; + + private SessionRepository sessionRepository; + + @BeforeEach + void setUp() { + sessionRepository = new JdbcSessionRepository(jdbcTemplate); + } + + @Test + void crud() { + + List testStudents = List.of(1L, 2L, 3L); + Session testSession = new Session(1L, + testStudents, + new PricingType(false, 0), + SessionState.valueOf("START"), + new SessionImage(new ImageCapacity(1024), ImageType.valueOf("gif"), + new ImageSize(300, 200)), + 10, + new SessionDate(LocalDateTime.now(), LocalDateTime.now().plusDays(2))); + + Long sessionPk = sessionRepository.save(testSession); + Session savedSession = sessionRepository.findById(sessionPk); + assertThat(savedSession.getStudents()).hasSameElementsAs(testStudents); + LOGGER.debug("Session: {}", savedSession); + } +} From aef0900e3c0d67d31514553890ad891e33d35f17 Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Wed, 6 Nov 2024 00:40:29 +0900 Subject: [PATCH 5/9] =?UTF-8?q?chore:=20README=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- STEP3README.md | 30 ++---------------------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/STEP3README.md b/STEP3README.md index fef380fdbb..a75f674989 100644 --- a/STEP3README.md +++ b/STEP3README.md @@ -2,10 +2,10 @@ ## step3 요구사항 -1. [ ] 앞단계에서 구현한 도메인 모델 DB와 매핑하고 데이터 저장 +1. [x] 앞단계에서 구현한 도메인 모델 DB와 매핑하고 데이터 저장 2. 2. 테이블 설계하고 객체매핑 -2. [ ] Payments는 테이블 매핑 미고려 +2. [x] Payments는 테이블 매핑 미고려 ## 관련 클래스 @@ -13,29 +13,3 @@ 2. jdbcCourseRepository 3. CourseRepositoryTest - - -## 테스트 필요 내용 - --이미지 크기는 1MB이하. --이미지 크기 1MB 초과 및 0이하 실패 --이미지타입 일치 불일치 테스트 --이미지 사이즈 테스트 - -- 무료강의 무제한 인원 테스트 - -## 피드백 - -1. 패키지명 소문자 컨벤션 -2. 클래스 내부 상수,변수와 메서드 개행으로 구분 -3. 생성 검증테스트시 불필요한 변수할당 제외하기 -4. 단위테스트간 독립성 유지하기. 테스트간 서로 영향을 주면 테스트가 어렵다. -5. 한줄이상 불필요 개행 제거 -6. 오해나 혼동을 줄 수 있는 클래스명이나 변수명 개선 -7. 맹목적인 일급컬렉션 사용대신, 의도에 맞게 사용하기.(ex: 일급컬렉션생성시 컬렉션만의 로직이 존재하면 래핑할 가치가 있음) -8. 커스텀 exception. 예외성성의 비용이 비싸다. 스택의 depth에 따라 10이면 4000나노초. 오버라이딩하면 80나노초. - 9. - 1. 커스텀 Exception 클래스에서 fillInStackTrace trace안하도록 오버라이딩하기 -> 커스텀Exception은 비즈니스로직 실패 방지용도이므로 call stack에 대한 - trace는 불필요하므로 - 10. static final로 exception들 new로 미리 생성. - 11. 핸들링이 필요한 영역에서 호출. \ No newline at end of file From e006874311e93ecbbfda9fc14d771df477c6bbc9 Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Wed, 6 Nov 2024 23:47:15 +0900 Subject: [PATCH 6/9] =?UTF-8?q?refactor:=20NamedParamegerJdbcTemplate?= =?UTF-8?q?=EB=A5=BC=20=ED=99=9C=EC=9A=A9=ED=95=98=EC=97=AC=20=EA=B0=80?= =?UTF-8?q?=EB=8F=85=EC=84=B1=20=EB=B0=8F=20=EC=95=88=EC=A0=84=ED=95=98?= =?UTF-8?q?=EA=B2=8C=20=EC=BD=94=EB=93=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- STEP3README.md | 6 +++ .../java/nextstep/courses/domain/Course.java | 6 +++ .../infrastructure/JdbcCourseRepository.java | 42 ++++++++++++------- .../infrastructure/CourseRepositoryTest.java | 6 +-- 4 files changed, 42 insertions(+), 18 deletions(-) diff --git a/STEP3README.md b/STEP3README.md index a75f674989..53d2378ac8 100644 --- a/STEP3README.md +++ b/STEP3README.md @@ -13,3 +13,9 @@ 2. jdbcCourseRepository 3. CourseRepositoryTest + +## 주요 피드백 +1. 숫자로 순서를 써서 하는건 실수 및 어려운 문제가 있음 +-> NamedParameterJdbcTemplate사용해보기 + +2. \ No newline at end of file diff --git a/src/main/java/nextstep/courses/domain/Course.java b/src/main/java/nextstep/courses/domain/Course.java index a533ec537a..dcf31f9395 100644 --- a/src/main/java/nextstep/courses/domain/Course.java +++ b/src/main/java/nextstep/courses/domain/Course.java @@ -45,6 +45,10 @@ public LocalDateTime getCreatedAt() { return createdAt; } + public int getClassNumber() { + return classNumber; + } + @Override public String toString() { return "Course{" + @@ -55,4 +59,6 @@ public String toString() { ", updatedAt=" + updatedAt + '}'; } + + } diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java index 20151d2cac..41065512dc 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java @@ -2,8 +2,10 @@ import nextstep.courses.domain.Course; import nextstep.courses.domain.CourseRepository; -import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import java.sql.Timestamp; @@ -11,30 +13,40 @@ @Repository("courseRepository") public class JdbcCourseRepository implements CourseRepository { - private JdbcOperations jdbcTemplate; + private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - public JdbcCourseRepository(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; + public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { + this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; } @Override public int save(Course course) { - String sql = "insert into course (title, creator_id, created_at, class_number) values(?, ?, ?,?)"; - return jdbcTemplate.update(sql, course.getTitle(), course.getCreatorId(), course.getCreatedAt(),1); + String sql = "insert into course (title, creator_id, created_at, class_number) " + + "values(:title, :creatorId, :createdAt, :classNumber)"; + SqlParameterSource parameterSource = new MapSqlParameterSource() + .addValue("title", course.getTitle()) + .addValue("creatorId", course.getCreatorId()) + .addValue("createdAt", course.getCreatedAt()) + .addValue("classNumber", course.getClassNumber()); + + return namedParameterJdbcTemplate.update(sql, parameterSource); } @Override public Course findById(Long id) { - String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = ?"; + String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = :id"; + + MapSqlParameterSource parameterSource = new MapSqlParameterSource() + .addValue("id",id); RowMapper rowMapper = (rs, rowNum) -> new Course( - rs.getLong(1), - rs.getString(2), - rs.getLong(3), - toLocalDateTime(rs.getTimestamp(4)), - toLocalDateTime(rs.getTimestamp(5)), - rs.getInt(6) - ); - return jdbcTemplate.queryForObject(sql, rowMapper, id); + rs.getLong("id"), + rs.getString("title"), + rs.getLong("creator_id"), + toLocalDateTime(rs.getTimestamp("created_at")), + toLocalDateTime(rs.getTimestamp("updated_at")), + rs.getInt("class_number") + ); + return namedParameterJdbcTemplate.queryForObject(sql, parameterSource, rowMapper); } private LocalDateTime toLocalDateTime(Timestamp timestamp) { diff --git a/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java b/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java index f087fc0ad2..265faefc89 100644 --- a/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java +++ b/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; -import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import static org.assertj.core.api.Assertions.assertThat; @@ -17,13 +17,13 @@ public class CourseRepositoryTest { private static final Logger LOGGER = LoggerFactory.getLogger(CourseRepositoryTest.class); @Autowired - private JdbcTemplate jdbcTemplate; + private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private CourseRepository courseRepository; @BeforeEach void setUp() { - courseRepository = new JdbcCourseRepository(jdbcTemplate); + courseRepository = new JdbcCourseRepository(namedParameterJdbcTemplate); } @Test From 3665cb303f041bf1d858aa1db0028a3454b94a22 Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Thu, 14 Nov 2024 00:06:51 +0900 Subject: [PATCH 7/9] =?UTF-8?q?refactor:=20=EC=BD=94=EB=93=9C=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=20=EA=B0=9C=EC=84=A0=201.=20=EB=B6=88=ED=95=84?= =?UTF-8?q?=EC=9A=94=20=EC=96=B4=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=20?= =?UTF-8?q?=EB=84=A4=EC=9D=B4=EB=B0=8D=20=EC=A0=9C=EA=B1=B0=202.=20Course?= =?UTF-8?q?=20=EC=83=9D=EC=84=B1=EC=9E=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/nextstep/courses/domain/Course.java | 6 ++++- .../infrastructure/JdbcCourseRepository.java | 24 +++++++++---------- .../infrastructure/JdbcSessionRepository.java | 4 ++-- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/nextstep/courses/domain/Course.java b/src/main/java/nextstep/courses/domain/Course.java index dcf31f9395..badecc0325 100644 --- a/src/main/java/nextstep/courses/domain/Course.java +++ b/src/main/java/nextstep/courses/domain/Course.java @@ -24,12 +24,16 @@ public Course(String title, Long creatorId) { } public Course(Long id, String title, Long creatorId, LocalDateTime createdAt, LocalDateTime updatedAt, int classNumber) { + this(id, title, creatorId, createdAt, updatedAt, classNumber, new ArrayList<>()); + } + + public Course(Long id, String title, Long creatorId, LocalDateTime createdAt, LocalDateTime updatedAt, int classNumber, List sessions) { this.id = id; this.title = title; this.creatorId = creatorId; this.createdAt = createdAt; this.updatedAt = updatedAt; - sessions = new ArrayList<>(); + this.sessions = sessions; this.classNumber = classNumber; } diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java index 41065512dc..3f8a6f13a5 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java @@ -14,6 +14,14 @@ @Repository("courseRepository") public class JdbcCourseRepository implements CourseRepository { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; + private final static RowMapper ROW_MAPPER = (rs, rowNum) -> new Course( + rs.getLong("id"), + rs.getString("title"), + rs.getLong("creator_id"), + toLocalDateTime(rs.getTimestamp("created_at")), + toLocalDateTime(rs.getTimestamp("updated_at")), + rs.getInt("class_number") + ); public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; @@ -35,21 +43,11 @@ public int save(Course course) { @Override public Course findById(Long id) { String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = :id"; - - MapSqlParameterSource parameterSource = new MapSqlParameterSource() - .addValue("id",id); - RowMapper rowMapper = (rs, rowNum) -> new Course( - rs.getLong("id"), - rs.getString("title"), - rs.getLong("creator_id"), - toLocalDateTime(rs.getTimestamp("created_at")), - toLocalDateTime(rs.getTimestamp("updated_at")), - rs.getInt("class_number") - ); - return namedParameterJdbcTemplate.queryForObject(sql, parameterSource, rowMapper); + MapSqlParameterSource parameterSource = new MapSqlParameterSource().addValue("id",id); + return namedParameterJdbcTemplate.queryForObject(sql, parameterSource, ROW_MAPPER); } - private LocalDateTime toLocalDateTime(Timestamp timestamp) { + private static LocalDateTime toLocalDateTime(Timestamp timestamp) { if (timestamp == null) { return null; } diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java index b7ebb77aac..f199c4247b 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java @@ -17,9 +17,9 @@ import java.util.ArrayList; import java.util.List; -@Repository("sessionRepository") +@Repository() public class JdbcSessionRepository implements SessionRepository { - private JdbcOperations jdbcTemplate; + private final JdbcOperations jdbcTemplate; public JdbcSessionRepository(JdbcOperations jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; From 2396f2265c550da6c375c5fec677c775246fb83d Mon Sep 17 00:00:00 2001 From: tjdjdjrdl123 Date: Thu, 14 Nov 2024 23:09:10 +0900 Subject: [PATCH 8/9] =?UTF-8?q?refactor:=20=EC=BD=94=EB=93=9C=EB=A6=AC?= =?UTF-8?q?=EB=B7=B0=20=EA=B0=9C=EC=84=A0=201.=20Session=20=ED=81=B4?= =?UTF-8?q?=EB=9E=98=EC=8A=A4=EC=97=90=20courseId=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/nextstep/courses/domain/Session.java | 7 ++-- .../infrastructure/JdbcCourseRepository.java | 32 +++++++++++++------ .../infrastructure/JdbcSessionRepository.java | 5 +-- src/main/resources/schema.sql | 1 + .../infrastructure/CourseRepositoryTest.java | 3 +- .../infrastructure/SessionRepositoryTest.java | 2 +- 6 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/main/java/nextstep/courses/domain/Session.java b/src/main/java/nextstep/courses/domain/Session.java index f97238abcf..6c3ca20ff2 100644 --- a/src/main/java/nextstep/courses/domain/Session.java +++ b/src/main/java/nextstep/courses/domain/Session.java @@ -15,11 +15,12 @@ public class Session { private SessionImage image; private int maxStudentCount; private SessionDate date; + private Long courseId; public Session(PricingType pricingType, int maxStudentCount, SessionState state, SessionDate date , SessionImage image) { - this(0L, new ArrayList(),pricingType,state,image,maxStudentCount,date); + this(0L, new ArrayList(),pricingType,state,image,maxStudentCount,date,0L ); } public Session(List students, PricingType pricingType, SessionState state, SessionImage image, int maxStudentCount, SessionDate date) { @@ -30,9 +31,10 @@ public Session(List students, PricingType pricingType, SessionState state, this.image = image; this.maxStudentCount = maxStudentCount; this.date = date; + this.courseId = 0L; } - public Session(Long id, List students, PricingType pricingType, SessionState state, SessionImage image, int maxStudentCount, SessionDate date) { + public Session(Long id, List students, PricingType pricingType, SessionState state, SessionImage image, int maxStudentCount, SessionDate date, Long courseId) { this.id = id; this.students = students; this.pricingType = pricingType; @@ -40,6 +42,7 @@ public Session(Long id, List students, PricingType pricingType, SessionSta this.image = image; this.maxStudentCount = maxStudentCount; this.date = date; + this.courseId = courseId; } public void requestSession(Payment payment) { diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java index 3f8a6f13a5..450edecd78 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java @@ -2,6 +2,7 @@ import nextstep.courses.domain.Course; import nextstep.courses.domain.CourseRepository; +import nextstep.courses.domain.Session; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @@ -10,21 +11,17 @@ import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; @Repository("courseRepository") public class JdbcCourseRepository implements CourseRepository { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; - private final static RowMapper ROW_MAPPER = (rs, rowNum) -> new Course( - rs.getLong("id"), - rs.getString("title"), - rs.getLong("creator_id"), - toLocalDateTime(rs.getTimestamp("created_at")), - toLocalDateTime(rs.getTimestamp("updated_at")), - rs.getInt("class_number") - ); - - public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate) { + private JdbcSessionRepository jdbcSessionRepository; + + public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate, JdbcSessionRepository sessionRepository) { this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; + this.jdbcSessionRepository = sessionRepository; } @Override @@ -43,10 +40,25 @@ public int save(Course course) { @Override public Course findById(Long id) { String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = :id"; + List sessions = new ArrayList<>();/*getSessions(id);*/ + RowMapper ROW_MAPPER = (rs, rowNum) -> new Course( + rs.getLong("id"), + rs.getString("title"), + rs.getLong("creator_id"), + toLocalDateTime(rs.getTimestamp("created_at")), + toLocalDateTime(rs.getTimestamp("updated_at")), + rs.getInt("class_number"), + sessions + ); MapSqlParameterSource parameterSource = new MapSqlParameterSource().addValue("id",id); return namedParameterJdbcTemplate.queryForObject(sql, parameterSource, ROW_MAPPER); } + /* private List getSessions(Long id) { + jdbcSessionRepository.findById() + } +*/ + private static LocalDateTime toLocalDateTime(Timestamp timestamp) { if (timestamp == null) { return null; diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java index f199c4247b..9d61bab101 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcSessionRepository.java @@ -82,7 +82,7 @@ public Session findById(Long id) { " session_state," + " image_capacity," + " image_type," + - " image_width, image_height, max_student_count, start_date, end_date from session where id = ?"; + " image_width, image_height, max_student_count, start_date, end_date, course_id from session where id = ?"; RowMapper rowMapper = (rs, rowNum) -> { long pk = rs.getLong(1); List students = findStudents(pk); @@ -93,7 +93,8 @@ public Session findById(Long id) { SessionState.valueOf(rs.getString(4)), new SessionImage(new ImageCapacity(rs.getInt(5)), ImageType.valueOf(rs.getString(6)), new ImageSize(rs.getInt(7),rs.getInt(8))), rs.getInt(9), - new SessionDate(toLocalDateTime(rs.getTimestamp(10)), toLocalDateTime(rs.getTimestamp(11)))); + new SessionDate(toLocalDateTime(rs.getTimestamp(10)), toLocalDateTime(rs.getTimestamp(11))) + ,rs.getLong(12) ); }; return jdbcTemplate.queryForObject(sql, rowMapper, id); diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index ddcb49ef8e..b2dd762693 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -20,6 +20,7 @@ create table session ( max_student_count int, start_date timestamp, end_date timestamp, + course_id int, primary key (id) ); diff --git a/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java b/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java index 265faefc89..1827ea9e3c 100644 --- a/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java +++ b/src/test/java/nextstep/courses/infrastructure/CourseRepositoryTest.java @@ -20,10 +20,11 @@ public class CourseRepositoryTest { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private CourseRepository courseRepository; + private JdbcSessionRepository jdbcSessionRepository; @BeforeEach void setUp() { - courseRepository = new JdbcCourseRepository(namedParameterJdbcTemplate); + courseRepository = new JdbcCourseRepository(namedParameterJdbcTemplate, jdbcSessionRepository); } @Test diff --git a/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java b/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java index cd706724a7..0a2d38f0be 100644 --- a/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java +++ b/src/test/java/nextstep/courses/infrastructure/SessionRepositoryTest.java @@ -43,7 +43,7 @@ void crud() { new SessionImage(new ImageCapacity(1024), ImageType.valueOf("gif"), new ImageSize(300, 200)), 10, - new SessionDate(LocalDateTime.now(), LocalDateTime.now().plusDays(2))); + new SessionDate(LocalDateTime.now(), LocalDateTime.now().plusDays(2)),1L ); Long sessionPk = sessionRepository.save(testSession); Session savedSession = sessionRepository.findById(sessionPk); From e32989aea00fbdb1b1e970e0f609f5243e538785 Mon Sep 17 00:00:00 2001 From: leewonsuk Date: Sat, 16 Nov 2024 01:09:32 +0900 Subject: [PATCH 9/9] =?UTF-8?q?feat:=20sessionid=EB=93=A4=EC=9D=84=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EB=8A=94=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94=20=EB=B0=8F=20=EC=BF=BC=EB=A6=AC=EB=AC=B8=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/CourseSessionRepository.java | 8 ++++ .../infrastructure/JdbcCourseRepository.java | 15 +++++--- .../JdbcCourseSesisonRepository.java | 37 +++++++++++++++++++ src/main/resources/schema.sql | 7 ++++ 4 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 src/main/java/nextstep/courses/domain/CourseSessionRepository.java create mode 100644 src/main/java/nextstep/courses/infrastructure/JdbcCourseSesisonRepository.java diff --git a/src/main/java/nextstep/courses/domain/CourseSessionRepository.java b/src/main/java/nextstep/courses/domain/CourseSessionRepository.java new file mode 100644 index 0000000000..9a80203891 --- /dev/null +++ b/src/main/java/nextstep/courses/domain/CourseSessionRepository.java @@ -0,0 +1,8 @@ +package nextstep.courses.domain; + +import java.util.List; + +public interface CourseSessionRepository { + int save(Long courseId, List sessionIds); + List findByCourseId(Long id); +} diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java index 450edecd78..e71bf2ea91 100644 --- a/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseRepository.java @@ -2,6 +2,7 @@ import nextstep.courses.domain.Course; import nextstep.courses.domain.CourseRepository; +import nextstep.courses.domain.CourseSessionRepository; import nextstep.courses.domain.Session; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -13,15 +14,18 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; @Repository("courseRepository") public class JdbcCourseRepository implements CourseRepository { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private JdbcSessionRepository jdbcSessionRepository; + private CourseSessionRepository courseSessionRepository; - public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate, JdbcSessionRepository sessionRepository) { + public JdbcCourseRepository(NamedParameterJdbcTemplate namedParameterJdbcTemplate, JdbcSessionRepository sessionRepository, CourseSessionRepository courseSessionRepository) { this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; this.jdbcSessionRepository = sessionRepository; + this.courseSessionRepository = courseSessionRepository; } @Override @@ -40,7 +44,7 @@ public int save(Course course) { @Override public Course findById(Long id) { String sql = "select id, title, creator_id, created_at, updated_at, class_number from course where id = :id"; - List sessions = new ArrayList<>();/*getSessions(id);*/ + List sessions = getSessions(id);/*getSessions(id);*/ RowMapper ROW_MAPPER = (rs, rowNum) -> new Course( rs.getLong("id"), rs.getString("title"), @@ -54,10 +58,11 @@ public Course findById(Long id) { return namedParameterJdbcTemplate.queryForObject(sql, parameterSource, ROW_MAPPER); } - /* private List getSessions(Long id) { - jdbcSessionRepository.findById() + private List getSessions(Long id) { + List sessionIds = courseSessionRepository.findByCourseId(id); + return sessionIds.stream().map(jdbcSessionRepository::findById).collect(Collectors.toList()); } -*/ + private static LocalDateTime toLocalDateTime(Timestamp timestamp) { if (timestamp == null) { diff --git a/src/main/java/nextstep/courses/infrastructure/JdbcCourseSesisonRepository.java b/src/main/java/nextstep/courses/infrastructure/JdbcCourseSesisonRepository.java new file mode 100644 index 0000000000..af3bca980a --- /dev/null +++ b/src/main/java/nextstep/courses/infrastructure/JdbcCourseSesisonRepository.java @@ -0,0 +1,37 @@ +package nextstep.courses.infrastructure; + +import nextstep.courses.domain.CourseSessionRepository; +import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +public class JdbcCourseSesisonRepository implements CourseSessionRepository { + + private final JdbcOperations jdbcTemplate; + + public JdbcCourseSesisonRepository(JdbcOperations jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + + @Override + public int save(Long courseId, List sessionIds) { + String sql = "insert into course_session (course_id, session_id) values(?,?)"; + int totalInsert = 0; + for (Long sessionId : sessionIds) { + int count = jdbcTemplate.update(sql, courseId, sessionId); + totalInsert += count; + } + return totalInsert; + } + + @Override + public List findByCourseId(Long courseId) { + String sql = "select session_id from course_session where course_id = ?"; + RowMapper rowMapper = (rs, rowNum) -> rs.getLong("session_id"); + return jdbcTemplate.query(sql,rowMapper, courseId); + } + +} diff --git a/src/main/resources/schema.sql b/src/main/resources/schema.sql index b2dd762693..ad148699c0 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/schema.sql @@ -32,6 +32,13 @@ create table session_students ( constraint unique_registration unique (id, session_id) ); +create table course_session ( + id bigint generated by default as identity + course_id bigint, + sesison_id bigint, + primary key (id) +) + create table ns_user ( id bigint generated by default as identity,