저번시간에는 JPA를 활용해보았다.
이번시간에는 스프링 데이터 JPA을 실습을 통해 배워보자 !
스프링 데이터 JPA 사용하게 되면 리포지토리 없이 인터페이스만으로도 개발을 완료할 수 있으며,
CRUD 기능도 스프링 데이터 JPA가 모두 제공하여 단순반복했던 개발 코드가 확연히 줄어든다!
⚠ 스프링 데이터 JPA는 JPA를 편리하게 사용할 수 있도록 도와주는 기술로 먼저 JPA 선행학습이 되어야한다!
1. 초기세팅
(1) 이전 시간에 사용한 JPA 설정을 그대로 사용
2. 코드작성
(1) 리포지토리 생성하기 - SpringDateJpaMemberRepository
package hello.helloSpring.repository;
import hello.helloSpring.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface SpringDateJpaMemberRepository extends JpaRepository<Member,Long>,MemberRepository {
@Override
Optional<Member> findyByName(String name);
}
SpringDateJpaMemberRepository 인터페이스는 스프링 데이터 JPA에서 제공하는 JpaRepository받는다.
이때 저장되는 Member클래스와 PK의 type인 Long을 명시해주고 MemberRepository 받는다.
그리고 findByName() 메서드만 인터페이스를 생성해준다.
이 상태에서 JPA 리포지토리를 사용하도록 스프링 설정을 변경하기 위해 Spring Config파일을 아래와 같이 변경한다.
(2) SpringConfig 코드 변경
package hello.hellospring;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.*;
import hello.hellospring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//import javax.persistence.EntityManager;
//import javax.sql.DataSource;
@Configuration
public class SpringConfig {
//private final DataSource dataSource;
//private final EntityManager em;
private final MemberRepository memberRepository;
public SpringConfig(MemberRepository memberRepository){
this.memberRepository = memberRepository;
}
@Bean
public MemberService memberService(){
return new MemberService(memberRepository);
}
// @Bean
// public MemberRepository memberRepository(){
// //return new MemoryMemberRepository();
// //return new JdbcMemberRepository(dataSource);
// //return new JdbcTemplateMemberRepository(dataSource);
// return new JpaMemberRepository(em);
// }
}
이상태에서 동작 테스트를 한다면, 엥? JPA 리포지토리를 사용할 때의 테스트 결과와 동일하다.
단순하게 인터페이스만을 생성해서 동작 가능하게 했던 이유는 JpaRepository을 extends 했기 때문이다.
즉 스프링 데이터 JPA에서 자동으로 인터페이스의 구현체를 만들고 스프링빈으로 자동 등록되었고
우리는 회원 리포지토리 스프링 빈을 Spring Config에서 회원 서비스에 주입하여 이를 사용했기 때문이다.
수업을 듣고 나의 표정....음? 에? 엥? 이게 뭔소리야....
역시 개발의 세계는 참... 어렵고 무궁무진하구나....JPA는 공부를 따로 해야겠다는 다짐을 했다.
다음 시간에는 AOP에 대해서 학습해보자 !
'ON > 실습' 카테고리의 다른 글
[Spring Boot] AOP (0) | 2023.11.30 |
---|---|
[Spring Boot] 스프링 DB 접근 기술 - JPA (0) | 2023.11.28 |
[Spring Boot] 스프링 DB 접근 기술 - 순수 JDBC 와 JdbcTemplate (0) | 2023.11.27 |
[Spring Boot] 회원 관리 예제 - 웹 MVC 개발 ① (0) | 2023.11.24 |
[Spring Boot] 스프링 빈과 의존관계 - 자바 코드로 직접 스프링 빈 등록하기 ② (0) | 2023.11.23 |