스프링 데이터 엑세스
1. 순수 JDBC
2. 스프링 JdbcTemplate
3. JPA
H2 데이터베이스 설치 방법
1) ./h2.bat
(mac에서는 ./h2.sh)
2) jdbc:h2:~/test
로 DB 생성
3) ~/test.mv.db
파일 생성 확인
4) 이후부터 jdbc:h2:tcp://localhost/~/test
로 접속
The Web Console server could not be started. Possible cause: another server is already running at XXX:8082
8082 포트가 겹쳐서 발생한 오류. 포트 죽여줘야함.
순수 JDBC
- build.gradle 파일에 jdbc, h2 데이터베이스 관련 라이브러리 추가
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
runtimeOnly 'com.h2database:h2'
- 스프링 부트 데이터베이스 연결 설정 추가 (
resources/application.properties
)
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
: sequence라고 생각하자- spring config 변경
@Bean public MemberRepository memberRepository() {
// return new MemoryMemberRepository();
return new JdbcMemberRepository(dataSource);
}
스프링 통합 테스트
- @SpringBootTest : 스프링 컨테이너와 테스트 함께 실행.
- @Transactional : 테스트 케이스에 이 애노테이션이 있으면, 테스트 시작 전에 트랜잭션을 시작, 테스트 완료 후에 항상 롤백. 다음 테스트에 영향 주지않기 위해 사용. (DB에 데이터가 남지 않음)
스프링 JdbcTemplate
- 스프링 JdbcTemplate과 MyBatis 같은 라이브러리는 JDBC API에서 본 반복 코드를 제거해준다. 하지만 SQL은 직접 작성.
- 순수 JDBC와 환경설정은 같다.
- spring config 변경
@Bean
public MemberRepository memberRepository() {
// return new MemoryMemberRepository();
// return new JdbcMemberRepository(dataSource);
return new JdbcTemplateMemberRepository(dataSource);
}
JPA
- 기존의 반복 코드는 물론이고, 기본적인 SQL도 JPA가 직접 만들어서 실행.
- SQL과 데이터 중심의 설계에서 객체 중심의 설계로 패러다임을 전환 가능하게 해준다.
- build.gradle 파일에 JPA, h2 데이터베이스 관련 라이브러리 추가
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
//implementation 'org.springframework.boot:spring-boot-starter-jdbc'
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'
}
}
spring-boot-starter-data-jpa 는 내부에 jdbc 관련 라이브러리를 포함
- 스프링 부트에 JPA 설정 추가(
resources/application.properties
)
spring.jpa.show-sql=true //JPA가 생성하는 SQL을 출력
spring.jpa.hibernate.ddl-auto=none //자동으로 테이블 생성하는 것 해제
- member 클래스 엔티티매핑
@Entity
public class Member {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) //DB가 알아서 생성되게 한 것을 identity전략이라고 함.
private Long id;
private String name;
- JpaMemberRepository 생성 (JPQL 사용)
- 서비스 계층에 트랜잭션 추가
- spring config 변경
@Configuration
public class SpringConfig {
private final DataSource dataSource;
private final EntityManager em;
public SpringConfig(DataSource dataSource, EntityManager em) {
this.dataSource = dataSource; 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);
}
}
스프링 데이터 JPA
- 리포지토리에 구현 클래스 없이 인터페이스 만으로 개발을 완료할 수 있다.
- 기본 CRUD 기능도 스프링 데이터 JPA가 모두 제공
- 앞의 JPA 설정을 그대로 사용
- 스프링 데이터 JPA 회원 리포지토리(인터페이스) 생성
- spring config 변경
@Configuration
public class SpringConfig {
private final MemberRepository memberRepository;
@Autowired
public SpringConfig(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Bean
public MemberService memberService(){
return new MemberService(memberRepository);
}
}
- 스프링 데이터 JPA가 SpringDatJpaMemberRepository 를 스프링 빈으로 자동 등록
인프런 '스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술' 통해 학습 중.
'JAVA' 카테고리의 다른 글
Spring 핵심 01 : 객체 지향 설계와 스프링 (0) | 2021.05.18 |
---|---|
Spring 05 : AOP (0) | 2021.05.18 |
Spring 03 : 스프링 빈과 의존관계 (0) | 2021.05.18 |
Spring02 : 예제(회원관리) (0) | 2021.05.18 |
Spring 01 : 프로젝트 환경설정 (0) | 2021.05.18 |