build.gradle
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
runtimeOnly 'mysql:mysql-connector-java'
...
}
· SQL > MyBatis Framework
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.3'
· SQL > JDBC API
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
· SQL > MySQL Driver
runtimeOnly 'mysql:mysql-connector-java'
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sample?characterEncoding=UTF-8&serverTimezone=UTC
username: user
password: password
mybatis:
type-aliases-package: com.example.sample
mapper-locations: mapper/*.xml
· type-aliases-package를 지정해주지 않으면 mapper xml 파일에서 resultType의 class를 package까지 모두 작성해주어야 한다. 아래의 sample.xml을 예로 들면 resultType="User" 가 아닌 resultType="com.example.sample.User" 이렇게 적어주어야 하는 번거로움이 있으므로 type-aliases-package를 지정해주는 것이 편리하다.
· mapper-locations에는 mapper xml 파일의 위치를 지정해주어 mapper xml 파일을 읽어들일 수 있도록 합니다.
sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sample">
<select id="getUser" resultType="User">
SELECT
LOGIN_ID as loginID,
USER_NM as userNm
FROM
USER
</select>
</mapper>
SampleDao.java
package com.example.sample;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class SampleDao {
@Autowired
private SqlSession sqlSession;
public User selectUser(){
return sqlSession.selectOne("sample.getUser");
}
}
User.java
package com.example.sample;
public class User {
private String loginId;
private String userNm;
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getUserNm() {
return userNm;
}
public void setUserNm(String userNm) {
this.userNm = userNm;
}
@Override
public String toString() {
return "User [loginId=" + loginId + ", userNm=" + userNm + "]";
}
}
SampleApplicationTests.java
package com.example.sample;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SampleApplicationTests {
@Autowired
private SampleDao sampleDao;
@Test
void test() {
User user = sampleDao.selectUser();
System.out.println(user);
}
}
user 테이블 Data
LOGIN_ID | USER_NM |
hong | 홍길동 |
출력화면
User [loginId=hong, userNm=홍길동]