MyBatis | What Is MyBatis? | Hello World

Installation

build.gradle

compile 'org.mybatis:mybatis:3.3.0'
compile 'mysql:mysql-connector-java:5.1.38'

Prepare the Database

This example uses MySQL 5.5.28.

test_table

id value
1 hoge
2 fuga
3 piyo

Folder Structure

.
├── src/main/
├── java
│   └── sample/mybatis/
│       └── Main.java
├── resources
│       ├── mybatis-config.xml
│       └── sample_mapper.xml
└── build.gradle

Configuration Files

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.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/test"/>
        <property name="username" value="test"/>
        <property name="password" value="test"/>
      </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="map">
    select * from test_table
  </select>
</mapper>

Implementation

Main.java

package sample.mybatis;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        // Load the root configuration file.
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            // Create a SqlSessionFactory from the configuration file.
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

            // Create a SqlSession from the SqlSessionFactory.
            try (SqlSession session = factory.openSession()) {
                // Execute SQL with the SqlSession.
                List<Map<String, Object>> result = session.selectList("sample.mybatis.selectTest");

                result.forEach(row -> {
                    System.out.println("---------------");
                    row.forEach((columnName, value) -> {
                        System.out.printf("columnName=%s, value=%s%n", columnName, value);
                    });
                });
            }
        }
    }
}

Execution Result

---------------
columnName=id, value=1
columnName=value, value=hoge
---------------
columnName=id, value=2
columnName=value, value=fuga
---------------
columnName=id, value=3
columnName=value, value=piyo

Explanation

Configuration Files

  • First, prepare the base configuration file that defines database connection information and related settings (mybatis-config.xml).
  • Next, prepare the file that defines SQL statements and how query results are mapped (sample_mapper.xml).

Implementation

  • First, read the configuration file (mybatis-config.xml) with SqlSessionFactoryBuilder.
  • Create a SqlSession with SqlSessionFactory.
  • Execute SQL with the SQL execution method provided by SqlSession (selectList()).
  • The first argument specifies the ID that identifies the SQL to execute (the statement ID).
  • The statement ID and return format are based on the information defined in sample_mapper.xml.
Instance Description Recommended scope
SqlSessionFactoryBuilder Its work is done once it creates a SqlSessionFactory. Method scope
SqlSessionFactory Create it once and continue using it. Application scope
SqlSession Not thread-safe. Close it after a series of SQL executions finishes. Request scope
Mapper instance Should be the same as SqlSession, but a slightly shorter scope is preferable. Method scope

Mapper will be described later

  • Method scope
    • Use the instance only inside the method, then discard it.
  • Request scope
    • In a web application, use the same instance only for a single request.
    • Do not allow other requests to reference it.
  • Application scope
    • Continue using the same instance while the application is running.