반응형
스프링 데이터 JPA는 JPA를 편리하게 사용하도록 도와주는 기술이기 때문에 먼저 JPA를 먼저 익혀야 한다.
앞의 JPA 설정을 그대로 사용한다.
SpringDataJpaMemberRepository 인터페이스 생성
인터페이스는 다중 상속이 가능하다.
스프링 데이터 JPA사용을 위해서 JpaRepository<Entity 클래스, PK 타입> 를 상속 받는다.
JpaRepository를 사용하면 스프링 데이터 JPA가 인터페이스에 대한 구현체를 만들어서 자동으로 빈 등록 해준다.
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
// 인터페이스가 인터페이스를 상속받을 때는 extends
// JpaRepository<Entity 클래스, PK 타입>
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.service;
import hello.hellospring.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import javax.xml.crypto.Data;
// 자바코드로 직접 스프링 빈 등록하는 방법
// 스프링 실행할때 자동 실행
@Configuration
public class SpringConfig {
// JDBC 사용을 위해 DataSource을 주입 받는다.
// private DataSource dataSource;
//
// @Autowired
// public SpringConfig(DataSource dataSource){
// this.dataSource = dataSource;
// }
// JPA사용을 위해 EntityManager을 주입 받는다.
// private EntityManager em;
//
// @Autowired
// public SpringConfig(EntityManager em) {
// this.em = em;
// }
// 스프링 데이터 JPA 사용을 위해 의존성 주입
private final MemberRepository memberRepository;
@Autowired
public SpringConfig(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
// 스프링 빈 등록
@Bean
public MemberService memberService() {
// @Autowired와 같이 동작
// return new MemberService(memberRepository());
// 스프링 데이터 JPA 사용
return new MemberService(memberRepository);
}
// @Bean
// public MemberRepository memberRepository() {
// // 구현체를 리턴해줌
//// return new MemoryMemberRepository();
//// JDBC 연결로 변경경
//// return new JdbcMemberRepository(dataSource);
//// JDBCTemplate 연결로 변경
//// return new JdbcTemplateMemberRepository(dataSource);
//// JPA 사용
//// return new JpaMemberRepository(em);
// }
}
JPQL = JPA를 이용하여 쿼리를 생성하여 돌릴 때 만들어지는 SQL -> 테이블이 아닌 객체를 검색하는 객체지향 쿼리
반응형
'코드로 배우는 스프링 부트 - 인프런' 카테고리의 다른 글
AOP (0) | 2022.08.24 |
---|---|
JPA (0) | 2022.08.22 |
스프링 JDBC Template (0) | 2022.08.19 |
스프링 통합 테스트 (0) | 2022.08.18 |
순수 JDBC (0) | 2022.08.17 |