상속의 개념
"extends"라는 단어를 Repository에서 보았다.
"클래스의 상속" 이라는 개념인데. 쉽게 말해 "이미 만들어둔거 가져다 쓰자!" 라고 선언하는 것이다.
class Person {
private String name;
private String getName() {
return this.name;
}
}
class Tutor extends Person {
private String address;
// Person 클래스를 상속했기 때문에,
// name 멤버변수와 getName() 메소드를 가지고 있습니다.
}
위 코드에서 Tutor는 Person을 상속받았기 때문에 Person의 변수인 name과 메소드인 getName()을 사용할 수 있다.
상속 연습하기
Course클래스가 course 테이블이 되는 것
Course클래스에 생성일자/ 수정일자 멤버를 추가해보자.
@MappedSuperclass // 상속했을 때, 컬럼으로 인식하게 합니다.
@EntityListeners(AuditingEntityListener.class) // 생성/수정 시간을 자동으로 반영하도록 설정
public abstract class Timestamped {
@CreatedDate // 생성일자임을 나타냅니다.
private LocalDateTime createdAt;
@LastModifiedDate // 마지막 수정일자임을 나타냅니다.
private LocalDateTime modifiedAt;
}
Timestamped라는 클래스는 createdAt과 modifiedAt멤버를 가지고
LocalDateTime이라는 자바의 시간을 나타내는 자료형이다
EntityListeners : 주시하다가 수정이 일어나면 자동으로 반영 <마지막 수정을 할때마다 실행>
MappedSuperclass : 상속할 때 컬럼으로 인식하게 해줘
abstract : 추상 -> 직접 구현 안되고 상속으로 구현해야함
Course 클래스에 아래와 같이 추가
class Course extends Timestamped
Week02Application클래스에 다음과같이 추가
@EnableJpaAuditing
@SpringBootApplication
public class Week02Application {

JPA 심화
CRUD
CRUD란? 정보관리의 기본 기능
→ 생성 (Create)
→ 조회 (Read)
→ 변경 (Update)
→ 삭제 (Delete)
- 데이터 저장하기 (Create) & 조회하기 (Read)
- Repository의 save와 findAll 등을 이용한다.
// 데이터 저장하기
repository.save(new Course("프론트엔드의 꽃, 리액트", "임민영"));
// 데이터 전부 조회하기
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("해당 아이디가 존재하지 않습니다.") //예외처리
);
Service의 개념
update, delete 로 넘어가기 전에, 다루어야 하는 개념이 바로 Service
- 스프링의 구조는 3가지 영역으로 나눌 수 있습니다.
- Controller : 가장 바깥 부분, 요청/응답을 처리함.
- Service : 중간 부분, 실제 중요한 작동이 많이 일어나는 부분
- Repo : 가장 안쪽 부분, DB와 맞닿아 있음.
- Update 는 Service 부분에 작성합니다.
public void update(Course course) {
this.title = course.title;
this.tutor = course.tutor;
}
Course클래스에 update메소드 추가
- src > main > java > com.sparta.week02 > service 패키지 생성
- 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();
}
}
CourseService.java에 다음과 같은 코드를 추가
데이터 변경하기 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); //update
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();
};
}
'공부기록 > 자바 스프링' 카테고리의 다른 글
| 2-1. 서버 설계 (API),(Repository),(Service),(Controller), (0) | 2022.01.23 |
|---|---|
| 2-0. 키워드 (0) | 2022.01.22 |
| 1-1. (RDBMS) (H2) (SQL) (JPA) (0) | 2022.01.21 |
| 0-2. 스프링으로 브라우저에 나타내보기 (0) | 2022.01.21 |
| 0-1. OT 스프링 시작하기 (0) | 2022.01.21 |