▶ 이번주차 간단 요약
▶ RDBMS?
→ RDBMS(Relational DataBase Management System)은 컴퓨터에 정보를 저장하고 관리하는 기술
→ 줄여서 RDB로, 관계형 데이터 베이스를 말한다. 정보 저장소 정도로 생각.
→ 컴퓨터에 정보 저장하는 것을 도와준다.
→ RDBMS의 종류 : MySQL, PostgreSQL, Oracle Database
▶ H2?
→ RDBMS의 한 종류로, 서버가 커져있는 동안에만 작동하는 RDB이다.
→ In-memory DB의 대표 주자
→ 인메모리 DB란 서버가 작동하는 동안에만 내용을 저장하고, 서버가 작동을 멈추면 데이터가 모두 삭제되는 데이터베이스를 말한다.
💻 H2 웹 콘솔 띄우기 : src > main > resources > application.properties
spring.h2.console.enabled=true //spring의 h2라는 DB에 웹 콘솔 보이게 해줘
spring.datasource.url=jdbc:h2:mem:testdb //spring의 data source로 h2를 쓸거야
→ http://localhost:8080/h2-console 로 접속하면 아래와 같은 화면 확인 가능
→ Connect 클릭
▶ SQL?
→ SQL은 데이터를 읽고, 저장하고, 변경하고, 삭제하는 구체적인 문법이다.
💻SQL 연습하기
→ 데이터베이스는 매우 고도화된 엑셀로, 엑셀 파일 하나가 "데이터베이스"라면, 엑셀 시트 하나는 "테이블"이라고 부르고, 엑셀 행 하나는 "데이터"라고 부른다.
→ 테이블 courses 생성하기
CREATE TABLE IF NOT EXISTS courses ( //courses란 Table이 존재 안하면 테이블을 만들어라.
id bigint(5) NOT NULL AUTO_INCREMENT, //AUTO_INCREMENT:만약에 id가 1이 들어왔으면, 다음 것은 2,3,4.... 자동으로 증가해라
title varchar(255) NOT NULL,
tutor varchar(255) NOT NULL,
PRIMARY KEY (id)
);
→ bigint = Long , varchar = string
→ courses 데이터 삽입
INSERT INTO courses (title, tutor) VALUES //INSERT INTO: courses에 넣어달라(괄호쌍이 맞도록)
('웹개발의 봄 , Spring', '남병관'), ('웹개발 종합반', '이범규');
→ courses 데이터 조회하기
SELECT * FROM courses;
▶ JPA?
→ JPA(Spring Data JPA)는 스프링을 위해 태어난 녀석
→ Java로 코드를 작성하면 SQL로 번역해줄 뿐만 아니라, 기본적인 기능이 거의 완벽하게 탑재
→ 즉, JPA는 SQL을 쓰지 않고 데이터를 생성, 조회, 수정, 삭제할 수 있도록 해주는 번역기이다.
→ Repository는 JPA를 작동시키는 매개체이다.
→ "테이블"은 Domain, "SQL"은 Repository이다.
💻Domain, Repository 도입하기
→ src > main > java > com.sparta.week02에 domain이라는 패키지 생성
→ Course.java, CourseRepository.java(interface) 파일 생성
Course.java
@NoArgsConstructor // 기본생성자를 대신 생성
@Entity // 테이블임을 나타낸다.
public class Course {
@Id // ID값, Primary Key로 사용하겠다는 뜻
@GeneratedValue(strategy = GenerationType.AUTO) //자동증가 명령
private Long id;
@Column(nullable = false) //컬럼이 값이고, 반드시 값이 존재해야 함을 나타냄
private String title;
@Column(nullable = false)
private String tutor;
public String getTitle() {
return this.title;
}
public String getTutor() {
return this.tutor;
}
public Course(String title, String tutor) {
this.title = title;
this.tutor = tutor;
}
}
CourseRepository.java 인터페이스
public interface CourseRepository extends JpaRepository<Course, Long> {
} //< , > -> 어떤 걸 대상으로 어떤걸 식별할 것인지
▶Interface란?
→ JPA는 Repository를 통해서만 사용할 수 있다.
→ 인터페이스는 클래스에서 멤버가 빠진, 메소드 모음집이라고 보면 된다.
💻JPA 사용해보기
→ application.properties 세팅
spring.jpa.show-sql=true //spring이 JPA로 작동할 때, SQL을 보여달란 뜻
→ JPA 실행코드
//main함수 아래에
@Bean
public CommandLineRunner demo(CourseRepository repository) { //이 repository(파라미터)가 모든 SQL작업을 한다.
return (args) -> {
};
}
▶ 상속?
→ "extends" 키워드 사용
→ "클래스의 상속"이라는 개념으로, "이미 만들어둔거 가져다 쓰자!" 라고 선언하는 것
💻 상속 연습해보기 - Timestamped
→ DB 기본 중의 기본은, "생성일자"와 "수정일자"를 필드로 가지는 것이다
→ Course클래스에 생성일자/수정일자 멤버를 추가해보자.
Timesptamped.java(domain 패키지)
@MappedSuperclass //상속했을 때, 컬럼으로 인식하게 한다
@EntityListeners(AuditingEntityListener.class) //생성/수정 시간을 자동으로 반영하도록 설정
public class Timestamped {
@CreatedDate //생성 일자임을 나타냄
private LocalDateTime createdAt;
@LastModifiedDate //마지막 수정 일자임을 나타냄
private LocalDateTime modifiedAt;
}
→ Course클래스 수정: 상속 추가
class Course extends Timestamped {
→ Week02Application 클래스 수정 : @추가
@EnableJpaAuditing //수정일자가 완벽하게 spring을 통해 반영됨
@SpringBootApplication
public class Week02Application {
▶ 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가지 영역으로 나눌 수 있다.
1. Controller : 가장 바깥 부분, 요청/응답을 처리함.
2. Service : 중간 부분, 실제 중요한 작동이 많이 일어나는 부분
3. Repo : 가장 안쪽 부분, DB와 맞닿아 있음. (Repository, Entity)
→ ⭐update는 Service 부분에 작성⭐한다.
💻Service 만들기
→ Course 클래스에 update메소드 추가
public void update(Course course) {
this.title = course.title;
this.tutor = course.tutor;
}
→ src > main > java > com.sparta.week02 > service 패키지 생성
→ CourseService.java 만들기 : update 해보기
@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();
}
}
→ Week02Application.java : 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();
};
}