본문으로 바로가기
반응형

 

 

자바 프로젝트에서 생성한 데이터들을 DB와 연동하고자 한다.

 

spring에서 제공하는 스프링 데이터 JPA 방식을 사용하여 

코드를 깔끔하게 작성해보고자 한다.

 

 

 

DB 연동은, 같은 동작을 수행하는 코드를

총 4단계에 거쳐서 기술하고자 한다.

 

 

 

그 마지막은 스프링 데이터 JPA를 활용하는 방법이다.

 

 

 

 

 

기존 코드(Service, Repository, Domain 등)는 아래 링크에서 

순차적으로 볼 수 있다

 

https://healthdevelop.tistory.com/entry/spring12

 

[Spring boot] 스프링 - 회원 가입, 회원 조회

간단한 회원관리 예제를 구현하고자 한다. 순서는 아래를 참조하면 된다. ● 회원관리 예제 - 백엔드 개발  1. 회원 도메인과 리포지토리 만들기  2. 회원 리포지토리 테스트 케이스 작성  3. 회

healthdevelop.tistory.com

 

 

 

 

 

 

 

 

 

1. 스프링 데이터 JPA 회원 리포지토리

 

 

위에서 설명했듯이, jpa는 ORM 기술 표준으로 사용되고 있다. 

 

jpa를 적용하기 위해선

작성했던 객체(domain) 클래스에 db를 매핑해주는 코드를 추가하여야 한다.

 

추가된 코드는 아래와 같다.

 

 

 

 

 

 

SpringDataJpaMemberRepository.interface

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 {
	 Optional<Member> findByName(String name);
}

 

이렇게 JpaRepository를 extends 하는

SpringDataJpaMemberRepository 인터페이스를 생성만 하면 끝이다(??)

 

 

스프링 데이터 JPA가 SpringDataJpaMemberRepository 를 스프링 빈으로 자동 등록해주는 것이다..

 

 

그래서 개발자는

JpaRepository에 이미 구현된 메소드들을 호출만 하면 된다.

(ex. save, findyById 등등)

 

 

 

 


 

SpringDataJpaMemberRepository 인터페이스 안에

 

Optional<Member> findByName(String name);

 

위 코드는 따로 삽입하였다.

 

 

이유는 entity에 기본키로 등록된 id로 member를 조회하거나 삭제, 등록하는 메소드들은

이미 등록 되었지만,

 

name은 기본키로 설정되어 있지않아,

name관련 db 작업을 하고 싶다면 메소드 명과 매개변수만 구현 해주면 된다.

 

 

 

 

 

 

 

 

 

 

2. Config 작성  

 

 

 

위에 작성한 코드들을 작성했던 memberRepository interface로 넘겨주어야 한다.

 

그것은 이전에 작성했던 config 파일을 수정해서 할 수 있다.

 

 

 

package hello.hellospring;
import hello.hellospring.repository.*;
import hello.hellospring.service.MemberService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
	 private final MemberRepository memberRepository;
 
 	public SpringConfig(MemberRepository memberRepository) {
 		this.memberRepository = memberRepository;
	 }
 
 	@Bean
 	public MemberService memberService() {
 		return new MemberService(memberRepository);
 	}
}

 

 

스프링 빈으로 자동 등록된 SpringDataJpaMemberRepository를 구현할 때 

memberRepository로 extends 받았다.

 

SpringConfig에 위와 같이 코드를 작성하면

스프링이 구현한 SpringDataJpaMemberRepository의 memberRepository를 주입해준다.

 

 

 

 

 

 


 

 

 

이제 데이터 연동은 마쳤고,

실제로 회원 가입이 잘 되는지 확인해 보자.

 

 

 

 

 

 

 


● 서버(브라우저)에서 확인

 

 

 

 

 

서버를 실행시키고,,

 

 

 

회원 가입을 페이지에 접속을 요청하고

 

 

 

 

 

 

 

 

 

 

새로운 회원 "jpa"를 등록시켜준다음

회원 조회 페이지로 가보면,,

 

 

 

 

 

 

 

 

 

 

새로운 회원이 "jpa"가 등록되었다.

 

 

 

 

 

 

 

 

 

h2 데이터베이스도 확인을 해보면

 

 

데이터가 잘 저장되었다.

 

 

 

 


 

 

 

우리(개발자)는 기존의 MemoryMemberRepository를 수정하지 않고

SpringConfig만 수정함으로써 db 저장소를 바꾸었다.

 

 

이것은 객체 지향 설계 5원칙 중 하나인 OCP(개방-폐쇄 원칙)을 잘 준수한 것이다.

 

 

기존에 있는 상태에서 확장은 하였지만, 기존 코드는 전혀 손을 대지 않았다.

 

 

 

이것이 스프링의 장점이다.



반응형