Notice
Recent Posts
Recent Comments
Link
«   2024/12   »
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 31
Tags more
Archives
Today
Total
관리 메뉴

요리사에서 IT개발자로

스파르타 부트캠프 JPA문제(다락방) 본문

Spring

스파르타 부트캠프 JPA문제(다락방)

H.S-Backend 2024. 6. 19. 21:47

1. Entity를 만들고 관계(단방향)를 설정해보세요.

  1. 학생필드 타입
    아이디 Long
    학번 String
    이름 String
    이메일 String
  2. 시험필드 타입
    고유번호 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를 구현해보세요.

  1. 학생을 등록한다.
  2. 등록한 학생을 조회한다.
  3. 등록한 학생의 과목타입(JPA) 과목 시험을 등록한다.
  4. 등록한 학생의 과목타입(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

 

GitHub - Hyungs0703/rest-api-practice

Contribute to Hyungs0703/rest-api-practice development by creating an account on GitHub.

github.com

 

반응형