프로그래머스
오늘의 에러
Error starting ApplicationContext.
private, public
Getter / Setter
// Getter
public String getTitle() {
return this.title;
}
// Setter
public void setTitle(String title) {
this.title = title;
}
JSON
JSON : 데이터를 서버에서 전달받는 형식
RestController : 데이터로 응답하려면 사용해야 함
@GetMapping
@RestController
public class CourseController {
@GetMapping("/courses") // 주소
public Course getCourses() {
Course course = new Course();
course.setTitle("제목");
course.setDays(00);
course.setTutor("이름");
return course;
}
}
1주차 숙제
숙제 설명
- 새로운 스프링 프로젝트를 만든다. (New Project ...)
- Person 클래스를 만든다.
- 3개 이상의 멤버 변수를 만든다. (name, age, address, job ...)
- 멤버 변수는 모두 private 이다.
- Getter, Setter를 만든다.
- PersonConroller를 만들고, http://localhost:8080/myinfo 에 나의 정보가 뜨도록 한다.
- Person.java, PersonController.java 를 제출한다.
Person.java
package com.sparta.week01homework.Entity;
public class Person {
// 멤버변수
private String name;
private int age;
private String job;
// getter
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public String getJob() {
return this.job;
}
// setter
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setJob(String job) {
this.job = job;
}
}
package com.sparta.week01homework.controller;
import com.sparta.week01homework.Entity.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PersonController {
@GetMapping("/myinfo")
public Person getPersons() {
Person person = new Person();
person.setName("홍길동");
person.setAge(20);
person.setJob("학생");
return person;
}
}
RDBMS(Relational DataBase Management System)
H2 Database
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
SQL
JPA
JAP : SQL을 쓰지 않고 데이터를 생성, 조회, 수정, 삭제할 수 있도록 해주는 번역기
설정
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
"테이블" == Domain(Entity)
"SQL" == Repository
CourseRepository.java 인터페이스
public interface CourseRepository extends JpaRepository<Course, Long> {
}
spring.jpa.show-sql=true
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL
상속
extends : 클래스의 상속, 이미 만들어 둔 것을 가져다 쓰자
생성일자, 수정일자
@MappedSuperclass // 상속했을 때, 컬럼으로 인식하게 합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/수정 시간을 자동으로 반영하도록 설정
public class Timestamped {
@CreatedDate // 생성일자임을 나타냅니다.
private LocalDateTime createdAt;
@LastModifiedDate // 마지막 수정일자임을 나타냅니다.
private LocalDateTime modifiedAt;
}
class Course extends Timestamped {
@EnableJpaAuditing // <- 추가!
@SpringBootApplication
public class Week02Application {
JPA 심화
--------------------------------------------------------------------------------
// Create
// 데이터 저장하기
repository.save(new Course("프론트엔드의 꽃, 리액트", "임민영"));
--------------------------------------------------------------------------------
// Read
// 데이터 전부 조회하기
List<Course> courseList = repository.findAll();
for (int i=0; i<courseList.size(); i++) {
Course course = courseList.get(i);
System.out.println(course.getId());
System.out.println(course.getTitle());
System.out.println(course.getTutor());
}
// 데이터 하나 조회하기
Course course = repository.findById(1L).orElseThrow(
() -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
);
--------------------------------------------------------------------------------
// Update
@Bean
public CommandLineRunner demo(CourseRepository courseRepository, CourseService courseService) {
return (args) -> {
courseRepository.save(new Course("프론트엔드의 꽃, 리액트", "임민영"));
System.out.println("데이터 인쇄");
List<Course> courseList = courseRepository.findAll();
for (int i=0; i<courseList.size(); i++) {
Course course = courseList.get(i);
System.out.println(course.getId());
System.out.println(course.getTitle());
System.out.println(course.getTutor());
}
Course new_course = new Course("웹개발의 봄, Spring", "임민영");
courseService.update(1L, new_course);
courseList = courseRepository.findAll();
for (int i=0; i<courseList.size(); i++) {
Course course = courseList.get(i);
System.out.println(course.getId());
System.out.println(course.getTitle());
System.out.println(course.getTutor());
}
};
}
--------------------------------------------------------------------------------
// Delete
@Bean
public CommandLineRunner demo(CourseRepository courseRepository, CourseService courseService) {
return (args) -> {
courseRepository.save(new Course("프론트엔드의 꽃, 리액트", "임민영"));
System.out.println("데이터 인쇄");
List<Course> courseList = courseRepository.findAll();
for (int i=0; i<courseList.size(); i++) {
Course course = courseList.get(i);
System.out.println(course.getId());
System.out.println(course.getTitle());
System.out.println(course.getTutor());
}
Course new_course = new Course("웹개발의 봄, Spring", "임민영");
courseService.update(1L, new_course);
courseList = courseRepository.findAll();
for (int i=0; i<courseList.size(); i++) {
Course course = courseList.get(i);
System.out.println(course.getId());
System.out.println(course.getTitle());
System.out.println(course.getTutor());
}
courseRepository.deleteAll();
};
}
스프링의 구조
Service
Course 클래스에 update 메소드 추가
public void update(Course course) {
this.title = course.title;
this.tutor = course.tutor;
}
CourseService.java
@Service // 스프링에게 이 클래스는 서비스임을 명시
public class CourseService {
// final: 서비스에게 꼭 필요한 녀석임을 명시
private final CourseRepository courseRepository;
// 생성자를 통해, Service 클래스를 만들 때 꼭 Repository를 넣어주도록
// 스프링에게 알려줌
public CourseService(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
@Transactional // SQL 쿼리가 일어나야 함을 스프링에게 알려줌
public Long update(Long id, Course course) {
Course course1 = courseRepository.findById(id).orElseThrow(
() -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
);
course1.update(course);
return course1.getId();
}
}
느낀 점
그래도 오늘 열심히 한 듯?! 나름 뿌듯하다,,
과제 엉망진창이라 고쳐야하는데
지금 바로 고치기엔 개념이 너무 부족해서ㅜㅜ 강의 먼저 들어야 할 듯,,
아직 한참 남았지만,, 과제2도 해야하지만,,ㅜ
할 게 너무 많다 빨리빨리 해야지! 제발 집중 좀 해~~