본문 바로가기

개발/Java & Spring

[Spring] Spring Boot + Mybatis 연동하기(Spring boot starter, mysql, mybatis, gradle)-개발일기A[2]

역시나 사담을 생략하고 싶으시다면 굵은 글씨만 보셔도 무관합니다


본격적인 DB작업을 하기 전

그동안 나는 JDBCTemplate을 사용했고, 지난 면접 때도 그랬고 MyBatis, JPA 등등의 ORM 프레임워크의 중요성을 깨달았다.(MyBatis는 ORM 프레임워크라고 하기는 어렵다는데 다시 공부해봐야겠다)


예전에 Spring+MyBatis(xml기반) 예제를 잠깐 따라하긴 했는데,

그땐 뭐가 뭔지 이해도 안하고 그냥 따라했던거라 이해도, 기억도 없다가 이번에 다시 하니까

되게 편하잖아? 심지어 mybatis에서 spring-boot-starter와 연동하도록 지원해주는 모듈이 있는데, 와 그걸로하니까 내가 손쓸게 거의없다!

나중에 Spring+Mybatis로도 해보긴 해야겠다 ㅋㅋㅋ 너무 쉽게갔어..


http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

을 참고했습니다


Spring starter project + Gradle(STS) 기반의 프로젝트 기반으로 진행합니다



먼저 build.gradle 파일에 의존성을 추가해줍니다.

dependencies {
    compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2")
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('mysql:mysql-connector-java')
}

첫 번째 의존이 mybatis에서 지원하는 spring boot start 연동 모듈,

그리고 jdbc, mysql 의존성까지 추가합니다


사실 저는 여기서

Failed to bind properties under 'spring.datasource.type' to java.lang.Class<javax.sql.DataSource>:

라는 에러가 났는데, 혹시 끝까지 따라해보시고 같은 에러가 난다면 spring-boot-starter:1.1.1 로 수정해보고 해보세요!

저는 이렇게 했더니 해결되었습니다 


mysql에 접속하기 위한 설정을 해줍니다.

저는 application.properties를 지우고 application.yml를  main/resources안에 다시 만들어 주고 yml형식으로 설정을 해주었어요!

spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/DB이름?autoReconnect=true&useSSL=false
    username: username(특별히 정해준적 없다면 root)
    password: userpassword

사실 대부분의 자료를 보면 저기에


type: org.apache.tomcat.jdbc.pool.DataSource


를 추가해주는데요, 저는 위에서도 언급했다시피 여기서 계속 에러가 나서 이 값을 지우고 모듈을 다운그레이드 해주었어요.

지금 생각해보니 그냥 이 값만 지웠어도 됐을 것 같기도 하고..? 

아 참고로 type을 생략해도 자동으로 DataSource를 찾아서 주입해준다고 합니다. 



여기 MyBatis-Spring-boot-Starter 에 관한 설명 찬찬히 읽어보면 아실 수 있어요!

  • Autodetect an existing DataSource.
  • Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean.
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory.
  • Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.



이제 Mapper만 생성하면 전부 끝나요!

자신의 Table Schema와 일치하는 형식으로 User class를 생성하고 해당 객체를 반환하는 Mapper Class를 생성해줍니다.

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM User WHERE id = #{id}")
    User findAll(@Param("id") String id);
}


오늘은 간단히 사용법만 알아본거였으니까 Controller에서 임의의 값을 집어 넣어볼게요.

Controller.java


	@Autowired
	UserMapper UserMapper;
	
	@RequestMapping(method=RequestMethod.GET, value="/")
	@ResponseBody
	public String test(){
		return UserMapper.findAll("abc").getPw();
	}

저렇게 자동 주입 처리를 해놓으면 알아서 Mapper를 매치해줘요!

아 정말 편하지 않나여? ㅠ 개발자 만세 


이제 이상태에서 실행하면

제가 설정한 해당 pw가 출력되네요!


대충 쓰는법 알고 굴러가는거 이해했으니 더 제대로 해봐야겠어욤!

혹시 Failed to bind properties under 'spring.datasource.type' to java.lang.Class<javax.sql.DataSource> 이 에러의 정확한 이유를 아시는 분이 계시다면 댓글 부탁드립니다~