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.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.kodejava.example.mybatis.domain.Record;


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();

The directory structure of the code above is:

├── pom.xml
└── src
    └── main
        ├── java
        │   └── org
        │       └── kodejava
        │           └── example
        │               └── mybatis
        │                   ├──
        │                   └── domain
        │                       └──
        └── 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


Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🙂.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.