[Practice! ] Minimum settings when using MyBatis

1. Prior knowledge

-[Even beginners can do it! ] How to install Eclipse on Windows 10 (Java environment construction) -[Practice! ] Display Hello World with Spring Boot -[Practice! ] Java database linkage (Connector / J 8.0.20)

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

2. Preparation

22.png 23.png

  1. Type cmd in the search box to launch 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 as shown in the image.

3. Create Spring Boot project

06.png

  1. Select [File (F)]-> [New (N)]-> [Spring Starter Project]. 02.png
  2. Enter MyBatisTest as the name, select Java version: 8 and click the Next> button. 03.png
  3. Select Spring Boot Version: 2.3.1, Lombok, JDBC API, MyBatis Framework, MySQL Driver, Thymeleaf, Spring Web and click the Done button. ..

4. Run the Spring Boot project

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 {
    //Read the root configuration file
	InputStream in = TestController.class.getResourceAsStream("/mybatis-config.xml");

	//Create SqlSessionFactory based on 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 mapper
  PUBLIC "-//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 shown in the folder structure above, 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 on MyBatisTest [boot] and select [Run] → [9 Spring Boot Application]. 01.png
  3. Access [localhost: 8080](http: // localhost: 8080 /), and if it looks like the image, it is successful.

5. Related

-[Useful to remember !!!] Easy creation of constructor and getter / setter in Eclipse -[Useful to remember !!!] Easy creation of inherited class in Eclipse -[Useful to remember !!!] Change MySQL character code -[Even beginners can do it! ] How to write Javadoc -[Easy-to-understand explanation! ] How to use Java overload -[Easy-to-understand explanation! ] How to use Java encapsulation -[Easy-to-understand explanation! ] How to use Java inheritance [Override explanation] -[Easy-to-understand explanation! ] Type conversion of reference type in Java -[Easy-to-understand explanation! ] How to use Java polymorphism -[Easy-to-understand explanation! ] How to use ArrayList [Java] -[Practice! ] Introduction of JFrame (explanation up to screen creation) -[Practice! ] Java database linkage (Connector / J 8.0.20) -[Practice! ] Execution of SQL statement -All about Java programming

Recommended Posts

[Practice! ] Minimum settings when using MyBatis
Scraping practice using Java ②
Scraping practice using Java ①
Error when using rails capybara
SpringBoot + Mybatis error when booting
Detailed tips when using Rails