2.Hello Spring Data JPA
스프링 데이터 JPA의 간단한 예시 코드
모델 클래스 Person
Person.java
@Entity
class Person {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
// getters and setters omitted for brevity
}Person 엔티티의 관리를 담당하는 저장소 인터페이스 PersonRepository
PersonRepository.java
// 영속성 인터페이스 PersonRepository 정의, Repository 인터페이스 확장
interface PersonRepository extends Repository<Person, Long> {
Person save(Person person); // Person 엔터티 저장 메서드 정의
Optional<Person> findById(long id); // id로 Person 조회 메서드 정의
}→ interface로 정의만 해도, 실행 시점에 실제 구현체(Implementation)가 자동으로 생성됨
메인 애플리케이션,
PeronRepository를 활용하여 Person 엔티티 생성 및 저장하는 로직 실행
DemoApplication.java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner runner(PersonRepository repository) {
return args -> {
// Person 더미 데이터 생성
Person person = new Person();
person.setName("Yoo");
// person 엔터티 저장(persist)
repository.save(person);
// 저장된 person 엔터티 조회
Person saved = repository.findById(person.getId()).orElseThrow(NoSuchElementException::new);
System.out.println(saved); // Yoo
};
}
}Last updated on