Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #대용량트래픽 #처리방법 #캐싱 #코드최적화 #db최적화 #트래픽 #로드밸런서
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #KDT #기본문법 #데이터베이스 #Computer #Science #CPU #메모리
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스
- 비트 #바이트 #이진수
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #웹개발
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #최종프로젝트 #aws s3 #프로필 이미지 수정 #자동삭제
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #ci #cd
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #tdd #테스트 주도개발 #테스트코드 #유닛테스트
- 프로세스 #CPU #시공유 #커널
- 쓰레드 #쓰레드풀 #프로세스
- 스파르타 코딩클럽 #내배캠 #최종프로젝트 #로그인 #인증인가 #jwt? #토큰인증 #액세스토큰 #리프레시토큰 #쿠키 #파싱 #서명키의 중요성 #security context holder
- 공간복잡도 #공간자원 #캐시메모리 #SRAM #DRAM #시간복잡도
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #springmvc패턴 #model #view #controller
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #get방식 #post방식 #http프로토콜 #클라이언트 #백엔드 #api
- 챌린저스 #bod
- 스프링 #백엔드 #자바
- 스파르타 코딩클럽 #내배캠 #최종프로젝트 #4개월삭제 #국비지원 #자바
- 인가 #
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #aop #관점지향프로그래밍 #유지보수
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #트랜잭션전파 #transaction
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #소셜로그인 #네이버 #기능구현 #vue.js #spring boot #네이버로그인 #연동하기
- spring security #jwt 토큰 #json web token #token #직렬화 #인증
- 보안 #이슈
- 스파르타 코딩클럽 #내배캠 #모의면접 #예상질문 #http 메서드 종류 #메서드 #post #put #get #patch #ci #ioc #의존성
- ci/cd파이프라인
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #OSI #ISO #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #DBMS #Oracle #MongoDB #아키텍쳐 #DB
- 스파르타 코딩클럽 #인메모리db #h2 #연동이슈 #문제해결 #방법 #spring security #header #
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #딥러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스
- java5기
- 스파르타코딩클럽 #부트캠프 #IT #백엔드 #머신러닝 #딥러닝 #AI #서버 #자동화 #SQL #기본문법 #데이터베이스 #DBMS #Oracle #MongoDB #아키텍쳐 #DB
Archives
- Today
- Total
요리사에서 IT개발자로
스파르타 부트캠프 JPA문제(다락방) 본문
1. Entity를 만들고 관계(단방향)를 설정해보세요.
- 학생필드 타입
아이디 Long 학번 String 이름 String 이메일 String - 시험필드 타입
고유번호 Long 학생_아이디 Long 점수 Float 과목타입 Enum 시험일 LocalDateTime JPA DB
Student
@Table
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String studentNumber;
@Column
private String name;
@Email
@Column
private String email;
TestEntity
@Table
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
@Column
private Float score;
//무조건 EnumType.STRING 으로만!!.
@Enumerated(value = EnumType.STRING)
private SubjectType subjectType;
@Column
private LocalDateTime examData;
SubjectType
public enum SubjectType {
JPA, DB
}
2. CRUD API를 구현해보세요.
- 학생을 등록한다.
- 등록한 학생을 조회한다.
- 등록한 학생의 과목타입(JPA) 과목 시험을 등록한다.
- 등록한 학생의 과목타입(JPA) 과목 시험을 조회한다.
StudentController
@RestController
@RequestMapping("/students")
public class StudentController {
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
//학생 등록.
@PostMapping
public ResponseEntity<?> addStudent(@RequestBody StudentRequestDto studentRequestDto) {
studentService.addStudent(studentRequestDto);
return ResponseEntity.status(HttpStatus.CREATED).body("학생 등록이 완료되었습니다.");
}
//학생 id로 조회
//(GET) /students/{id}
@GetMapping("/{id}")
public ResponseEntity<?> getStudentById(@PathVariable Long id) {
StudentResponseDto studentResponseDto = studentService.getStudentById(id);
return ResponseEntity.status(HttpStatus.OK).body(studentResponseDto);
}
StudentService
@Service
public class StudentService {
private final StudentRepository studentRepository;
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
//학생정보 저장
public void addStudent(StudentRequestDto studentRequestDto) {
studentRepository.save(new Student(studentRequestDto));
}
//학생 정보 조회
public StudentResponseDto getStudentById(Long id) {
Student student = studentRepository.findById(id).orElseThrow(() ->
new IllegalArgumentException("해당 학생은 존재하지 않습니다"));
return new StudentResponseDto(student);
}
}
StudentResponseDto
@Getter
public class StudentResponseDto {
private String studentNumber;
private String name;
private String email;
public StudentResponseDto(Student student) {
this.studentNumber = student.getStudentNumber();
this.name = student.getName();
this.email = student.getEmail();
}
}
StudentRequestDto
@Getter
@AllArgsConstructor
public class StudentRequestDto {
private String studentNumber;
private String name;
private String email;
}
학생등록
학생 조회
Test
@Table
public class Test {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
@Column
private Float score;
//무조건 EnumType.STRING 으로만!!.
@Enumerated(value = EnumType.STRING)
private SubjectType subjectType;
@Column
private LocalDateTime examData;
public Test(Student student, TestRequestDto testRequestDto) {
this.student = student;
this.score = testRequestDto.getScore();
this.subjectType = testRequestDto.getSubjectType();
}
Controller
@RestController
@RequestMapping("/tests")
public class TestController {
public TestController(TestService testService) {
this.testService = testService;
}
private final TestService testService;
//저장
@PostMapping("/{studentId}")
public ResponseEntity<?> studentAddTest(@PathVariable Long studentId, @RequestBody TestRequestDto testRequestDto) {
TestResponseDto testResponseDto = testService.studentAddTest(studentId, testRequestDto);
return ResponseEntity.status(HttpStatus.CREATED).body(testResponseDto);
}
//전체 조회
@GetMapping("/{studentId}")
public ResponseEntity<?> studentGetTests(@PathVariable Long studentId, @RequestBody CheckTestRequestDto requestDto) {
List<TestResponseDto> testList = testService.studentGetTests(studentId, requestDto);
return ResponseEntity.status(HttpStatus.OK).body(testList);
}
}
Service
@Service
public class TestService {
private final TestRepository testRepository;
private final StudentRepository studentRepository;
public TestService(TestRepository testRepository, StudentRepository studentRepository) {
this.testRepository = testRepository;
this.studentRepository = studentRepository;
}
//시험저장
public TestResponseDto studentAddTest(Long studentId, TestRequestDto testRequestDto) {
Student student = studentRepository.findById(studentId).orElseThrow(() ->
new IllegalArgumentException("해당 학생은 존재하지 않습니다"));
if (!(testRequestDto.getSubjectType().equals(SubjectType.DB) || testRequestDto.getSubjectType().equals(SubjectType.JPA))) {
throw new IllegalArgumentException("해당 과목은 존재하지 않습니다");
}
Test test = new Test(student, testRequestDto);
testRepository.save(test);
return new TestResponseDto(test);
}
//학생 시험조회 조회
public List<TestResponseDto> studentGetTests(Long studentId, CheckTestRequestDto requestDto) {
if (!(requestDto.getSubjectType().equals(SubjectType.DB) || requestDto.getSubjectType().equals(SubjectType.JPA))) {
throw new IllegalArgumentException("해당 과목은 존재하지 않습니다");
}
List<Test> studentTestList = testRepository.findAllByStudentId(studentId);
return studentTestList.stream()
.map(s -> new TestResponseDto(s.getSubjectType(), s.getScore()))
.toList();
}
}
TestResponseDto
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class TestResponseDto {
//과목 타입
private SubjectType subjectType;
//시험 점수
private Float score;
public TestResponseDto(Test test) {
this.subjectType = test.getSubjectType();
this.score = test.getScore();
}
}
TestRequestDto
@Getter
public class TestRequestDto {
private Float score;
private SubjectType subjectType;
}
CheckTestSubjectTypeRequestDto
@Getter
public class CheckTestSubjectTypeRequestDto {
private SubjectType subjectType;
}
학생 점수 등록
학생 과목과 점수조회
3. Query Method를 작성하고 예상 SQL을 작성해보세요.
ex)
- findById
- select *
- from entity where id = {id}
학번과 이메일로 조회한다.
findByStudentNumberAndStudentEmail(Long studentNumber, String studentEmail)
select *
from Student
where studentNumber = 10 and email = 'sparta@email.com'
김씨 성의 학생들을 조회한다.
findByNameStartsWith("김") // 사용할 때
findByNameStartsWith(String name);
select *
from Student
where name Like "김%"
점수가 70점 이상이고 80점 이하인 시험들을 내림차순으로 정렬하여 조회한다.
findByScoreBetweenOrderByScoreDesc(70, 80) //상관없다
findByScoreGreaterThanEqualAndScoreLessThanEqualOrderByScoreDesc(Long score1, Long score2)
findByScoreGreaterThanEqualAndScoreLessThanEqualOrderByScoreDesc(70, 80) //사용할 때
select *from Test
where score between 70 and 80
order by score desc
https://github.com/Hyungs0703/rest-api-practice
반응형
'Spring' 카테고리의 다른 글
SQL 쿼리 delete메소드 작동에 대해 (0) | 2024.06.25 |
---|---|
PasswordEncoder 한 비밀번호를 비교해주는 matches와 이유 (0) | 2024.06.21 |
스파르타 부트캠프 Query Method (다락방) (0) | 2024.06.18 |
스파르타 부트캠프 연관관계 맵핑 (다락방) (0) | 2024.06.18 |
스파르타 부트캠프 Entity 맵핑 (다락방) (0) | 2024.06.18 |