서버의 Repository, JPA, Model
SQL를 쓰지 않고 데이터를 생성, 조회, 수정, 삭제할 수 있도록 해주는 번역기
(자바를 이용해서 할 수 있음)
MySQL에서 Table - 엑셀 시트 해당, sql-그걸 조회
Spring에서 Domain - table, Repository - SQL이라고 볼 수 있다.
대부분의 Repositoty와 domain은 models 패키지 안에 만든다.
@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;
}
}
@Entity // 테이블임을 나타냅니다. → “데이터베이스 기준으로 테이블 역할을 할 클래스야”
@NoArgsConstructor // 기본생성자를 대신 생성해줍니다.
→기본 생성자를 자동으로 넣어줘라
테이블을 만드는 과정
@Column - > 테이블의 하나의 컬럼(열)이 된다고 표시
nullable = False → NOT NULL
@GeneratedValue(strategy = GenerationType.AUTO) // 자동 증가 명령입니다.
→AUTO_INCREMENT
각필드에 대해 GETTER
ID는 데이터베이스에서 쓰는거기때문에 GETTER, SETTER 해주지않는다.
public interface CourseRepository extends JpaRepository<Course, Long> {
}
CourseRepository에 JPA에 해당하는 코드가 만들어진것
CourseRepository → SQL을 대신하는 것 → Course에 관한 Repository다
JpaRepository → 이기능을 extend하겠다.
<Course라는 녀석이고, id의 형태가 Long이다>
일단 JPA는 인터페이스에서만 사용할 수 있다.
인터페이스는 클래스에서 멤버가 빠진 메소드 모음집이다.
JPA를 써보기위해 몇가지 작업이 필요하다.
spring.jpa.show-sql=true
jpa가 sql을 , 자바명령어를 sql로 바꿔서 직접 실행하는걸 보여주기 위해 스프링이 jpa 작동을 할때 sql을 보여달라
week02Application에
// Week02Application.java 의 main 함수 아래에 붙여주세요.
@Bean
public CommandLineRunner demo(CourseRepository repository) {
return (args) -> {
Course course1 = new Course("웹개발의 봄", "남병관");
repositoty.save(course1);
List<Course> courseList = repository.findAll();
};
}
저장하고, select 때려서 coursList 안에있는거 가져옴
이해를 위해 작성한 코드)
import com.sparta.week02.domain.Course;
import com.sparta.week02.domain.CourseRepository;
List<Course> courseList = repository.findAll();
→repository가 select 때리고 전부다 courseList안에 있는거 가져온것
for(int i=0;i<courseList.size();i++){
System.out.println(courseList.get(i));
}
course class를 만들고, 저장하고, 불러와서 , 하나하나 찍어보는 숙달에 집중하기
Course course1 = new Course("웹개발의 봄 Spring","남병관");
repository.save(course1);
List<Course> courseList = repository.findAll();
for(int i=0;i<courseList.size();i++){
Course c = courseList.get(i);
System.out.println(c.getTitle());
System.out.println(c.getTutor());
여기까지 하고 실행
h2-console에서 select 때려보면 조회할 수 있다.