마이바티스는 자바 퍼시스턴스 프레임워크 중 하나이다. 규모가 작은 프로그램에서는 jdbc로도 충분히 개발이 가능하지만, 기능이 여러가지로 복잡한 프로그램은 반복적으로 구현해야할 SQL 쿼리도 많고 복잡하기 때문에 더 편리하게 사용할 수 있도록 개발되었다.
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'
runtimeOnly 'mysql:mysql-connector-java:8.0.25'
# database
spring.datasource.url=jdbc:mysql://localhost:3306/{데이터베이스 이름}?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password={password}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 설정 파일
mybatis.config=mybatis-config.xml
mybatis.mapper-locations=mybatis/mapper/*.xml
아래와 같이 mybatis 폴더를 생성하여 하위에 넣어 준다.
mybatis-config.xml 내용
마이바티스 관련 정보를 설정하는 파일이다.
mappers 태그 안에 사용할 mapper.xml 이름을 넣어주면 된다.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="TodoMapper.xml"/>
</mappers>
</configuration>
먼저 MySQL 서버에 테이블을 만들어 놓는다.
Todo 클래스도 자료형에 맞춰서 생성한다.
Service 클래스 생성
Controller
localhost:8080/todo로 접속하면 todo 테이블에 저장되어 있던 값들이 보이게 하였다.
TodoMapper를 인터페이스로 생성한다.
그 다음 전에 만들었던 mapper 폴더로 이동하여 TodoMapper.xml 파일을 생성해 아래와 같은 내용을 추가해 준다. namespace는 전에 작성했던 Mapper 인터페이스 이름을 써주면 된다.
<?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="com.mardi2020.todoapp.Todo.TodoMapper">
<select id="getTodoAll" resultType="TodoDTO">
SELECT * FROM Todo;
</select>
</mapper>
resource에 todo 폴더를 추가하여 todoList.html을 작성해준다.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<table>
<thead>
<tr>
<th>title</th>
<th>Todo</th>
</tr>
</thead>
<tbody>
<tr th:each="todo : ${todos}">
<td th:text="${todo.title}"></td>
<td th:text="${todo.memo}"></td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>