[Java] [Practice! ] Minimal settings when using MyBatis

3 minute read

1. Prior knowledge

As prior knowledge, the contents of the above link are required.

2. Preparation

22.png 23.png

  1. Enter cmd in the search box to start the command prompt. 07.png
  2. Login with mysql -u username -p. 08.png 09.png

test.sql


create database test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

use test;

CREATE TABLE test1(
    id TINYINT ZEROFILL NOT NULL AUTO_INCREMENT,
    name VARCHAR(50),
    PRIMARY KEY(id));

INSERT INTO `test1`(`name`) VALUES ("test1");
INSERT INTO `test1`(`name`) VALUES ("test2");
INSERT INTO `test1`(`name`) VALUES ("test3");
INSERT INTO `test1`(`name`) VALUES ("test4");
  1. Copy the above SQL statement and execute it in the command prompt.
  2. Success if Query OK appears like the image.

3. Creating a Spring Boot project

06.png

  1. Select [File]→[New]→[Spring Starter Project]. 02.png
  2. Enter MyBatisTest for the name, select Java version: 8 and click the Next > button. 03.png
  3. Spring Boot version: 2.3.1 ,Lombok ,JDBC API ,MyBatis Framework ,MySQL Driver ,Thymeleaf ,Spring Web, and click the Finish button. ..

4. Spring Boot project execution

folder structure


MyBatisTest
└─ src
     └─ main
          ├─ java
          │ └─ com
          │ └─ example
          │ └─ demo
          │ ├─ Entity.java
          │ └─ TestController.java
          └─ resources
               ├─ application.properties
               ├─ mybatis-config.xml
               ├─ sample_mapper.xml
               │
               ├─ static
               └─ templates
                    └─ index.html

Entity.java


package com.example.demo;

import lombok.Data;

@Data
public class Entity {
private int id;
private String name;
}

TestController.java


package com.example.demo;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class TestController {
    // Load the root configuration file
InputStream in = TestController.class.getResourceAsStream("/mybatis-config.xml");

// Create SqlSessionFactory based on the configuration file
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

// Generate SqlSession from SqlSessionFactory
SqlSession session = factory.openSession();

    @GetMapping("/")
    public String index(Model model) {

    // execute SQL using SqlSession
    List<Entity> result = session.selectList("sample.mybatis.selectTest");

        model.addAttribute("Test", result);
        return "index";
    }
}

application.properties


spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=JST
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

mybatis-config.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>
  <environments default="sample_id">
    <environment id="sample_id">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/test?serverTimezone=JST"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="sample_mapper.xml"/>
  </mappers>
</configuration>

sample_mapper.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sample.mybatis">
  <select id="selectTest" resultType="com.example.demo.Entity">
    select * from test1
  </select>
</mapper>

index.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
  <head>
    <title>Test</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <ul>
      <li th:each="entity :${Test}">
        [[${entity.getId()}]]
        [[${entity.getName()}]]
      </li>
    </ul>
  </body>
</html>
  1. Arrange the files as the above folder structure, right-click MyBatisTest [boot] and select [Run]→[5 Maven install]. 15.png
[INFO] ----------------------------------------------- -------------------------
[INFO] BUILD SUCCESS
[INFO] ----------------------------------------------- -------------------------
[INFO] Total time: 4.125 s
[INFO] Finished at: 2020-07-05T21:50:22+09:00
[INFO] ----------------------------------------------- -------------------------
  1. Success if the above statement is displayed on the console. ‥ 16.png
  2. Right-click MyBatisTest [boot] and select [Run] → [9 Spring Boot application]`. 01.png
  3. Access localhost:8080 and if it looks like the image, it is successful.