How do I create an SqlSessionFactory object in MyBatis?

The example below shows you how to create MyBatis SqlSessionFactory object using an xml configuration. The steps required is to create the configuration file. This file basically contains the connection information to the database and MyBatis configuration such as typeAliases and the mappers.

The next steps is to read the configuration file using a class. This information then passes as the argument to the build() method of the SqlSessionFactoryBuilder class. The build() method return an SqlSessionFactory object.

package org.kodejava.mybatis;

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


public class SqlSessionFactoryDemo {
    public static void main(String[] args) throws IOException {
        // A resource file for MyBatis configuration.
        Reader reader = Resources.getResourceAsReader("configuration.xml");

        // Creates an SqlSessionFactoryBuilder. This builder need only 
        // create one time during the application life time.
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // Creates an instance of SqlSessionFactory. This object can be 
        // used to initiate an SqlSession for querying information from 
        // the mapped query.
        SqlSessionFactory factory =;
        System.out.println("factory = " + factory);

Below is an example of MyBatis configuration file:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration
    PUBLIC "-// Config 3.0//EN"
        <typeAlias alias="record" type="" />
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost/musicdb" />
                <property name="username" value="root" />
                <property name="password" value="" />
        <mapper resource="org/kodejava/mybatis/mapper/RecordMapper.xml" />

Maven Dependencies

    <!-- -->
    <!-- -->

Maven Central Maven Central

Leave a Reply

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