Search
Duplicate

[Spring 입문] 순수 JDBC 사용 및 연동

상태
스프링입문
담당자
속성 1
Spring
JAVA
MVC
jdbc
속성
8
1) JDBC 연동
Jdbc를 연동하기 위해서는 예전 시간에 만들어 놓았던 SrpingConfig.java 파일이 필요하다.
DataSource는 spring이 application.properties의 환경설정 값을 토대로 스프링 컨테이너에 빈으로 등록하기 때문에 아래와 같이 Autowired로 DI의존성 주입을 받을 수 있다.
package hello.hellospring; 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.sql.DataSource; @Configuration public class SpringConfig { private DataSource dataSource; @Autowired public SpringConfig(DataSource dataSource) { this.dataSource = dataSource; } ... }
Java
복사
2) 순수 JDBC 구성
여기서 주의해야 될 점은 getConnection(): 이다. 이전의 트랜잭션과 겹치는 상황이 발생할 수 있므로 항상 DataSourceUtils.getConnection을 통해서 Connection을 받아야 된다.
Code
3) 메모리에서 DB로 변경시키기
여기서 놀라운 경험을 할 수 있을 것이다. 기존에 SpringConfig에 설명을 할 때 DB를 언제든지 변경 가능하게 하기 위해서 SpringConfig로 작성한다고 하였다. 이는 아래 예제처럼 Repository의 빈만 변경하면 아무런 소스 변경 없이 바로 DB를 변경할 수 있다.
package hello.hellospring; import hello.hellospring.repository.JdbcMemberRepository; import hello.hellospring.repository.MemberRepository; 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.sql.DataSource; @Configuration public class SpringConfig { private DataSource dataSource; @Autowired public SpringConfig(DataSource dataSource) { this.dataSource = dataSource; } ... @Bean public MemberRepository memberRepository() { //return new MemoryMemberRepository();return new JdbcMemberRepository(dataSource); } }
Java
복사
결론
SpringConfig의 환경설정만 변경해서 Repository를 바로 변경 할 수 있다는 점 Spring 자체로 잘 쓰면 정말 유연한 코딩이 가능하다는 것을 알 수 있었고, 각각의 동작들이 정리를 통해서 좀 더 머릿속에 확립되는 것 같다.
이 글은 인프런의
제목 : 스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술
강사 : 김영한 님의 동영상을 참조해 만들었습니다.