- JPA 기술을 사용하면 SQL 쿼리도 JPA가 자동으로 생성해줌
- SQL,데이터 중심 설계 -> 객체 중심 설계
- 개발 생산성을 크게 높일 수 있음
- jpa는 자바의 표준 인터페이스중 하나이고 여러 업체에서 구현함. 우리는 주로 hibernate를 쓰게 됨
- ORM : object와 relational database table을 mapping함
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.12'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'hello'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '11'
}
repositories { // 아래 있는 라이브러리들을 어디서 다운받을지 정한것 (mavenCentral)
mavenCentral()
}
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-jdbc' // jdbc 라이브러리
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' //jpa 라이브러리(jdbc 포함)
runtimeOnly 'com.h2database:h2'
}
tasks.named('test') {
useJUnitPlatform()
}
- jdbc 라이브러리를 주석처리하고 jpa 라이브러리를 추가함
application.properties
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
#jpa가 날리는 쿼리를 보여줄지
spring.jpa.show-sql=true
# 테이블을 자동으로 만들지. 현재는 만들어져있는 테이블을 사용함. create로 바꾸면 테이블까지 자동으로 만들어줌
spring.jpa.hibernate.ddl-auto=none
- jpa 관련 설정을 추가해줌
- 참고 : application.properties는
#
을 이용해 주석처리함
spring.jpa.show-sql=true
는 jpa가 날리는 쿼리를 보기 위해 설정한 것
spring.jpa.hibernate.ddl-auto=none
는 이미 db에 테이블을 만들어놔서 none
으로 한 것이고 create
로 바꾸면 테이블까지 생성해주게 할 수 있음
Member.java
package hello.hellospring.domain;
import org.springframework.context.annotation.Primary;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.security.Identity;
@Entity //JPA에서 관리하는 Entity가 됨
public class Member {
//Entity는 Id가 필요함
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) // DB가 알아서 자동생성해줌
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
JpaMemberRepository
package hello.hellospring.repository;
import hello.hellospring.domain.Member;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
public class JpaMemberRepository implements MemberRepository{
//JPA는 EntityManager로 작동함 . 스프링부트가 자동으로 EntityManager를 생성해줌
private final EntityManager em;
// 만들어진것을 의존성 주입 받는것임
public JpaMemberRepository(EntityManager em) {
this.em = em;
}
@Override
public Member save(Member member) {
em.persist(member);
return member;
}
@Override
public Optional<Member> findById(Long id) {
Member member = em.find(Member.class ,id);
return Optional.ofNullable(member);
}
@Override
public Optional<Member> findByName(String name) {
List<Member> result = em.createQuery("select m from Member m where m.name = :name",Member.class)
.setParameter("name",name)
.getResultList();
return result.stream().findAny();
}
@Override
public List<Member> findAll() {
//select m from Member m : jpql 문법 . jpql은 객체를 대상으로 쿼리를 날리는 것
return em.createQuery("select m from Member m",Member.class).getResultList();
}
}
- pk 기반이 아닌 것들은 jpql 쿼리를 작성해 줘야함
- jpql 쿼리는 객체를 대상으로 쿼리를 날리는 것임
MemberService
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Transactional
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
//회원 가입
public Long join(Member member){
//이름이 중복되는 회원이 없어야함
validateDuplicateMember(member);
memberRepository.save(member);
return member.getId();
}
private void validateDuplicateMember(Member member) {
memberRepository.findByName(member.getName())
.ifPresent(m->{
throw new IllegalStateException("이미 존재하는 회원입니다");
});
}
//전체 회원 조회
public List<Member> findMembers(){
return memberRepository.findAll();
}
public Optional<Member> findOne(Long memberId){
return memberRepository.findById(memberId);
}
}
- jpa를 사용하려먼 서비스 계층에
@Transactional
어노테이션을 달아 줘야 함
- 모든 데이터 변경이 트랜잭션 안에서 수행되어야 함
SpringConfig
package hello.hellospring;
import hello.hellospring.repository.*;
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 DataSource dataSource;
// @Autowired
// public SpringConfig(DataSource dataSource){
// this.dataSource = dataSource;
// }
private EntityManager em;
@Autowired
public SpringConfig(EntityManager em) {
this.em = em;
}
@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);
}
}
테스트
package hello.hellospring.service;
import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import hello.hellospring.repository.MemoryMemberRepositoryTest;
import org.assertj.core.api.AssertJProxySetup;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@Transactional
class MemberServiceTest {
@Autowired MemberService memberService;
@Autowired MemberRepository memberRepository;
@Test
void 회원가입() {
// given 주어진 것
Member member = new Member();
member.setName("spring");
// when 실행한 것
Long saveId = memberService.join(member);
// then 나온 결과
Member findMember = memberService.findOne(saveId).get();
Assertions.assertThat(member.getName()).isEqualTo(findMember.getName());
}
@Test
public void 중복_회원_예외(){
//given
Member member1 = new Member();
member1.setName("spring");
Member member2 = new Member();
member2.setName("spring");
//when
memberService.join(member1);
//람다식의 로직을 실행할 때 IllegalStateException이 발생해야 함
//이렇게 작성하면 try-catch 형식으로 쓰지 않아도 됨
IllegalStateException e = assertThrows(IllegalStateException.class, () -> memberService.join(member2));
Assertions.assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다");
}
}
- 전에 만들어놓은 스프링부트 통합 테스트코드로 테스트함