우선 Repository 를 만든다
domain > CourseRepository.java 생성
package com.sparta.week01_hwk.domain;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<Course, Long> {
}
//JpaRepository는 앞서 언급했던 CRUD 처리를 위한 공통 인터페이스이다.
//이 인터페이스를 상속받은 인터페이스만 생성하면 해당 엔티티에 대한 CRUD를 공짜로 사용할 수 있게된다
//제네릭에는 엔티티 클래스와 엔티티 클래스가 사용하는 식별자 타입을 넣어주면 된다.
JapReposity 인터페이스를 상속하는데 제네릭에 <Entity(sql table)클래스, 식별자의 타입>을 넣어준다.
domain > Timestamped.java 예제 생성
package com.sparta.week01_hwk.domain;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.LocalDateTime;
@MappedSuperclass // 이 클래스를 상속했을 때, 컬럼으로 인식하게 한다.
@EntityListeners(AuditingEntityListener.class) // 개체를 주시하다가 변동시 생성,수정 시간을 자동으로 반영하도록 설정
public abstract class Timestamped {
@CreatedDate // 생성일자임을 나타냅니다.
private LocalDateTime createdAt;
@LastModifiedDate // 마지막 수정일자임을 나타냅니다.
private LocalDateTime modifiedAt;
}
Application.java 에서 테스트 해보기
package com.sparta.week01_hwk;
import com.sparta.week01_hwk.domain.Course;
import com.sparta.week01_hwk.domain.CourseRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import java.util.List;
@EnableJpaAuditing// 생성, 수정에 따라 자동 업데이트 사용하겠다.
@SpringBootApplication
public class Week02HwkApplication {
public static void main(String[] args) {
SpringApplication.run(Week02HwkApplication.class, args);
}
// Week02Application.java 의 main 함수 아래에 붙여주세요.
@Bean
public CommandLineRunner demo(CourseRepository repository) {
return (args) -> {
Course course1 = new Course("자바의 봄 Spring", "홍유찬");
repository.save(course1);
List<Course> courseList = repository.findAll();
for(int i=0; i<courseList.size(); i++){
Course p = courseList.get(i);
System.out.println(p.getTitle());
System.out.println(p.getName());
}
};
}
}
서버 재시작 후 H2 데이터 베이스에서 확인해보면 생성, 변경 칼럼이 추가된것을 확인 할 수 있다.
'H2' 카테고리의 다른 글
JPA CRUD (0) | 2020.11.15 |
---|---|
JPA 사용해보기 (0) | 2020.11.15 |
JPA 시작하기 (0) | 2020.11.15 |
H2 웹콘솔 띄우기 (0) | 2020.11.14 |