[SpringBoot] Mybatis & h2 connection test
1. 프로젝트 생성하기
- Gradle
 - Intellij 커뮤니티
 - Java 16
 - Spring Boot 2.5.2
 - Dependencies
- H2 Database
- JDBC API
- Lombok

 
2. 프로젝트 구조

3. resources/application.yml DB 속성 설정

1) cmd 혹은 git bash 로 H2/bin 파일 들어가서 - (window) ./h2.bat 실행 (mac) .h2.sh 실행 2) 실행시 H2 화면 팝업 - 최초 DB 생성시 url = jdbc:h2~/jdbc 입력 - 생성후 로그아웃 후 url = jdbc:h2:tcp://localhost/~/jdbc 변경 해서 접속
4. mybatis
spring framework에서 mybatis를 사용하기 위해서는 context-mapper.xml 등 설정 파일들을 많이 생성해줘야 한다. 그러나 springboot에서는 따로 파일 생성을 해주지 않아도 되기 때문에 파일 구성도 간단 해지고 조금더 코드에 집중 할 수 있다.
[resource] maven repository 사이트에서 Compile Dependencies를 확인해보면 mybatis-spring-boot-autoconfigure 이라는 것이 포함되어져 있다. Detail 한 내용은 [mybatis]에서 확인 할 수 있다.
그럼 spring framework에서 생성 했던 xml 파일을 생성 하지 않고 어떻게 사용을 할 수 있게 된것일까? 바로! mybatis dependency가 해주기 때문이다. 아래의 내용은 사이트에서 가져온 것이다. 번역을 잘 못해서 그대로 가져왔다. 
그럼 간단한 member 조회 기능을 구현해서 mybatis 테스트를 진행.
5. Member 구현 select query 테스트
@Mapper
public interface MemberMapper {
    @Select("SELECT * FROM MEMBER")
    List<Member> findAll();
    @Select("SELECT * FROM MEMBER WHERE id=#{id}")
    Member findById(@Param("id") Long id);
}
mapper interface 클래스를 만들고 MemberRepository 클래스에 mapper field를 만들어주면 된다.
@Repository
public class MemberRepository {
    private MemberMapper mapper;
    @Autowired
    public MemberRepository(MemberMapper mapper) {
        this.mapper = mapper;
    }
    public List<Member> findAll() {
        return mapper.findAll();
    }
    public Member findById(Long id) {
        return mapper.findById(id);
    }
}
나머지 코드는 GIT
클라이언트 사이드를 구현하지 않았으므로 postman으로 테스트를 진행했다. 간단한 select를 하기 위해서 H2 database에 data를 insert 해두었다.

postman 테스트 결과
아래와 같이 findAll() 조회가 잘 된것을 확인 할 수 있다.

그리고 findById() 조회도 잘 된것을 확인 할 수 있다.

Author And Source
이 문제에 관하여([SpringBoot] Mybatis & h2 connection test), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@brianhwang/SpringBoot-JDBC를-사용한-DB접속저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)