Spring/스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

[ 스프링 DB 접근 기술 ] 스프링 데이터 JPA

alsruds 2023. 9. 17. 05:27

🙂강의🙂

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8

 

[무료] 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링 웹 애플리케이션 개발 전반을 빠르게 학습할 수 있습니다., 스프링 학습 첫 길잡이! 개발 공부의 길을 잃지 않도록 도와드립니다. 📣 확인해주세

www.inflearn.com

 

💡 스프링 데이터 JPA 💡
➡️ 리포지토리에 구현 클래스 없이 인터페이스 만으로 개발 완료 가능
➡️ 기본 CRUD 기능 제공

⚠️주의⚠️
스프링 데이터 JPA 는 JPA 를 편리하기 사용하도록 도와주는 기술이므로 JPA 를 먼저 학습해야 함

 

  • 앞의 JPA 설정을 그대로 사용

 

[ 스프링 데이터 JPA 회원 리포지토리 ]

✅ src/main/java/hello.hellospring/repository 에 SpringDataJpaMemberRepository 인터페이스 생성하기

package hello.hellospring.repository;

import hello.hellospring.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

// 인터페이스는 다중 상속 가능
public interface SpringDataJpaMemberRepository extends JpaRepository<Member, Long>, MemberRepository {

    // select m from Member m where m.name = ?
    @Override
    Optional<Member> findByName(String name);
}

 

[ 스프링 설정 변경 ]

✅ SpringConfig 코드 수정하기

package hello.hellospring;

import hello.hellospring.repository.JpaMemberRepository;
import hello.hellospring.service.MemberService;
import hello.hellospring.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {

    // 만들어 놓은 SpringDataJpaMemberRepository 구현체가 세팅된다
    // -> 스프링 데이터 JPA 가 스프링 빈으로 자동 등록
    private final MemberRepository memberRepository;

    @Autowired
    public SpringConfig(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }

    @Bean
    public MemberService memberService() {
        return new MemberService(memberRepository);
    }

}

 

✅ 테스트 하기

성공 !

 

[ 스프링 데이터 JPA 제공 클래스 ]

클래스 구현 없이도 개발 가능 !!

 

[ 스프링 데이터 JPA 제공 기능 ]

  1. 인터페이스를 통한 기본 CRUD
  2. findByName(), findByEmail() 처럼 메서드 이름 만으로 조회 가능
  3. 자동 페이징 기능

 

참고 : 실무에서는 JPA 와 스프링 데이터 JPA 를 기본으로 사용하고, 복잡한 동적 쿼리는 Querydsl 이라는 라이브러리를 사용한다. Querydsl 사용 시 쿼리를 자바 코드로 안전하게 작성할 수 있고, 동적 쿼리도 편리하게 작성할 수 있다. 이외는 JPA 가 제공하는 네이티브 쿼리를 사용하거나, 스프링 JdbcTemplate 을 사용하면 된다.