How do I create MyBatis SqlSession object?

To create an SqlSession you can use the SqlSessionFactory class openSession() method. This method offers some overloaded method that can configure the property of the session. For example we can cofigure the auto-commit-mode and the transaction-isolation-level for the session.

package org.kodejava.example.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.kodejava.example.mybatis.domain.Record;

import java.io.IOException;
import java.io.Reader;

public class SqlSessionDemo {
    public static void main(String[] args) throws IOException {
        SqlSessionDemo demo = new SqlSessionDemo();

        // Build an SqlSessionFactory.
        SqlSessionFactory factory = demo.getSessionFactory();

        // Create an SqlSession by using the factory.openSession() method.
        // It is a good practice to use a try-with-resources block when
        // working with an SqlSession. The session will be automatically
        // closes when it finishes the job.
        try (SqlSession session = factory.openSession()) {
            Record record = session.selectOne("getRecord", 1L);
            System.out.println("Record = " + record);
        }
    }

    /**
     * Build an SqlSessionFactory.
     *
     * @return an SqlSessionFactory.
     * @throws IOException when fail to read the configuration file.
     */
    private SqlSessionFactory getSessionFactory() throws IOException {
        Reader reader = Resources.getResourceAsReader("configuration.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        return builder.build(reader);
    }
}

The directory structure of the code above is:

├── pom.xml
└── src
    └── main
        ├── java
        │   └── org
        │       └── kodejava
        │           └── example
        │               └── mybatis
        │                   ├── SqlSessionDemo.java
        │                   └── domain
        │                       └── Record.java
        └── resources
            ├── configuration.xml
            └── org
                └── kodejava
                   └── example
                        └── mybatis
                            └── mapper
                                └── RecordMapper.xml

For the configuration, mapper and the pojo you can check the following links:

Maven Dependencies

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.42</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply