Spring - DB 접근 기술 JPA(6)

1 분 소요

스프링 DB 접근 기술 JPA

  • JPA를 사용하면 SQL과 데이터 중심의 설계에서 객체 중심의 설계로 패러다임을 전환 할 수 있다.

    👉 개발 생산성 높아짐

build.gradle 에 JPA, 데이터베이스 관련 라이브러리 추가
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	runtimeOnly 'com.h2database:h2'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}
스프링 부트에 JAP 설정 추가

resources> application.properties

spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
JPA 엔티티 매핑

main> java> hello.hellospring> domain> Member.java

package hello.hellospring.domain;

import javax.persistence.*;

@Entity
public class Member {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // @Column(name = "username") db에 username이라면 이렇게 mapping 해주면 된다.
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
스프링 데이터 JPA 회원 레포지토리
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);
}
스프링 설정 변경

main> java> hello.hellospring> SpringConfig.java

package hello.hellospring;

import hello.hellospring.repository.JpaMemberRepository;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.service.MemberService;
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;

@Configuration
public class SpringConfig {

    private final MemberRepository memberRepository;
    
 	public SpringConfig(MemberRepository memberRepository) {
 		this.memberRepository = memberRepository;
	}
	@Bean
 	public MemberService memberService() {
 		return new MemberService(memberRepository);
 	}
}
  • Spring 데이터 JPA가 SpringDataJpaMemberRepository를 스프링 빈으로 자동 등록해준다.

스프링 데이터 JPA 제공 기능

  • 인터페이스를 통한 기본적인 CRUD

  • findByName() findByEmail() 처럼 메서드 이름 만으로 조회 기능 제공

    (select m from Member m where m.name = ?) 자동으로 이렇게 됨

참고자료

인프런 - 스프링 입문 (김영한)

카테고리:

업데이트:

댓글남기기