How do I build SqlSessionFactory without XML?

MyBatis comes with a complete configuration classes that allows us to create a configuration object programmatically without using the XML file. In this code snippet you’ll see how to create a SqlSessionFactory object without XML configuration file.

We start by obtaining a javax.sql.DataSource object. Then we create a TransactionFactory object. With these two objects we can then create an Environment object and specify its name, such as development, for development environment. The final step is to create the Configuration object using the previously created environment.

In the Configuration object we can define information such as the type aliases and register all the MyBatis mappers.

package org.kodejava.mybatis;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.TypeAliasRegistry;
import org.kodejava.mybatis.support.Record;

import javax.sql.DataSource;

public class BuildSqlSessionFactory {

    public static void main(String[] args) {
        // Get DataSource object.
        DataSource dataSource = BuildSqlSessionFactory.getDataSource();

        // Creates a transaction factory.
        TransactionFactory trxFactory = new JdbcTransactionFactory();

        // Creates an environment object with the specified name, transaction
        // factory and a data source.
        Environment env = new Environment("dev", trxFactory, dataSource);

        // Creates a Configuration object base on the Environment object.
        // We can also add type aliases and mappers.
        Configuration config = new Configuration(env);
        TypeAliasRegistry aliases = config.getTypeAliasRegistry();
        aliases.registerAlias("record", Record.class);

        config.addMapper(RecordMapper.class);

        // Build the SqlSessionFactory based on the created Configuration object.
        // Open a session and query a record using the RecordMapper.
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);

        try (SqlSession session = factory.openSession()) {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Record record = mapper.getRecord(1L);
            System.out.println("Record = " + record);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns a DataSource object.
     *
     * @return a DataSource.
     */
    public static DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost/musicdb");
        dataSource.setUsername("music");
        dataSource.setPassword("s3cr*t");
        return dataSource;
    }
}

Below are the other supporting classes for the code above, Record and RecordMapper.

package org.kodejava.mybatis;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.kodejava.mybatis.support.Record;

public interface RecordMapper {
    /**
     * Get a single record from the database based on the record
     * identifier.
     *
     * @param id record identifier.
     * @return a record object.
     */
    @Select("SELECT * FROM record WHERE id = #{id}")
    @Results(value = {
            @Result(property = "id", column = "id"),
            @Result(property = "title", column = "title"),
            @Result(property = "releaseDate", column = "release_date"),
            @Result(property = "artistId", column = "artist_id"),
            @Result(property = "labelId", column = "label_id")
    })
    Record getRecord(Long id);
}
package org.kodejava.mybatis.support;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Long id;
    private String title;
    private Date releaseDate;
    private Long artistId;
    private Long labelId;

    // Getters & Setters

    @Override
    public String toString() {
        return "Record{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", releaseDate=" + releaseDate +
                ", artistId=" + artistId +
                ", labelId=" + labelId +
                '}';
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I use @Select annotation in MyBatis?

In the previous example How do I create MyBatis mapper? you’ve seen how to use a mapper to get a record from the database. In that example the select query is defined in the mapper xml file. For the same functionality MyBatis also offer a solution to use an annotation for the select query.

In this example we will use the @Select annotation to define the query. To map the query result we can use the @ResultMap annotation where the value passed to this annotation is the result map id that we’ve defined in the mapper xml file.

Let see an example of a mapper interface definition that use an annotation to get a record from database:

package org.kodejava.mybatis;

import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.kodejava.mybatis.support.Record;

public interface RecordMapper {
    /**
     * Get a single Record from the database based on the record
     * identified.
     *
     * @param id record identifier.
     * @return a record object.
     */
    @Select("SELECT * FROM records WHERE id = #{id}")
    @ResultMap("recordResultMap")
    Record getRecord(int id);
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create MyBatis mapper?

In this example you will see how to create or define a data mapper using the MyBatis. The mapper will communicate our application with the underlying databases where the data is stored. MyBatis data mapper is defined as an interface object. We can either use annotations or the xml mapper to define our database query.

In the first steps we will create a domain object, a simple pojo to store our data in the object world. The attributes / fields of our pojo resemble the structure of our records table in the database.

package org.kodejava.mybatis.support;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Long id;
    private String title;
    private Date releaseDate;
    private Long artistId;
    private Long labelId;

    // Getters & Setters

    @Override
    public String toString() {
        return "Record{" +
            "id=" + id +
            ", title='" + title + '\'' +
            ", releaseDate=" + releaseDate +
            ", artistId=" + artistId +
            ", labelId=" + labelId +
            '}';
    }
}

Next we define the mapper interface code, we’ll create a RecordMapper.java file that contains a method to get data from the table. At this time the interface will be as the following:

package org.kodejava.mybatis;

import org.kodejava.mybatis.support.Record;

public interface RecordMapper {
    /**
     * Get a single Record from the database based on the record
     * identified.
     * 
     * @param id record identifier.
     * @return a record object.
     */
    Record getRecord(Long id);
}

After create the ResultMapper.java interface we create a RecordMapper.xml file that defines the queries used by our mapper. Here is how it looks like:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.kodejava.mybatis.RecordMapper">

    <resultMap id="recordResultMap" type="record">
        <result column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="release_date" property="releaseDate"/>
        <result column="artist_id" property="artistId"/>
        <result column="label_id" property="labelId"/>
    </resultMap>

    <select id="getRecord" parameterType="java.lang.Long" resultMap="recordResultMap">
        SELECT id,
            title,
            release_date,
            artist_id,
            label_id
        FROM record
        WHERE id = #{id}
    </select>
</mapper>

To tell MyBatis about our mapper we need to define the mapper inside MyBatis configuration file (resources/configuration.xml). We register the mapper inside the <mappers> element of the configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="record" type="org.kodejava.mybatis.support.Record" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <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="music" />
                <property name="password" value="s3cr*t" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/mybatis/mapper/RecordMapper.xml" />
    </mappers>
</configuration>

Finally, we create a simple application to use the data mapper to get record data from the database.

package org.kodejava.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.mybatis.support.Record;

import java.io.Reader;

public class MusicClient {

    public static void main(String[] args) throws Exception {
        Reader reader = Resources.getResourceAsReader("configuration.xml");

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(reader);

        try (SqlSession session = factory.openSession()) {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Record record = mapper.getRecord(1L);
            System.out.println("Record = " + record);
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

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

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

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 lifetime.
        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 = builder.build(reader);
        System.out.println("factory = " + factory);

        try (SqlSession session = factory.openSession()) {
            RecordMapper mapper = session.getMapper(RecordMapper.class);
            Record record = mapper.getRecord(1L);
            System.out.println("Record = " + record);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Below is an example of MyBatis configuration file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="record" type="org.kodejava.mybatis.support.Record" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <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="music" />
                <property name="password" value="s3cr*t" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/mybatis/mapper/RecordMapper.xml" />
    </mappers>
</configuration>

Below are the other supporting files and classes for the code above, RecordMapper.xml, RecordMapper and Record.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.kodejava.mybatis.RecordMapper">

    <resultMap id="recordResultMap" type="record">
        <result column="id" property="id"/>
        <result column="title" property="title"/>
        <result column="release_date" property="releaseDate"/>
        <result column="artist_id" property="artistId"/>
        <result column="label_id" property="labelId"/>
    </resultMap>

    <select id="getRecord" parameterType="java.lang.Long" resultMap="recordResultMap">
        SELECT id,
            title,
            release_date,
            artist_id,
            label_id
        FROM record
        WHERE id = #{id}
    </select>
</mapper>
package org.kodejava.mybatis;

import org.kodejava.mybatis.support.Record;

public interface RecordMapper {
    /**
     * Get a single record from the database based on the record
     * identifier.
     *
     * @param id record identifier.
     * @return a record object.
     */
    Record getRecord(Long id);
}
package org.kodejava.mybatis.support;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Long id;
    private String title;
    private Date releaseDate;
    private Long artistId;
    private Long labelId;

    // Getters & Setters

    @Override
    public String toString() {
        return "Record{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", releaseDate=" + releaseDate +
                ", artistId=" + artistId +
                ", labelId=" + labelId +
                '}';
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

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 configure the auto-commit-mode and the transaction-isolation-level for the session.

package org.kodejava.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.mybatis.support.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);
    }
}

Below are the configuration, mapper and the POJO.

  • configuration.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="record" type="org.kodejava.mybatis.support.Record" />
    </typeAliases>
    <environments default="dev">
        <environment id="dev">
            <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="music" />
                <property name="password" value="s3cr*t" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/mybatis/mapper/RecordMapper.xml" />
    </mappers>
</configuration>
  • RecordMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.kodejava.mybatis.RecordMapper">

    <resultMap id="recordResultMap" type="record">
        <result column="id" property="id" />
        <result column="title" property="title" />
        <result column="release_date" property="releaseDate" />
        <result column="artist_id" property="artistId" />
        <result column="label_id" property="labelId" />
    </resultMap>

    <select id="getRecord" parameterType="java.lang.Long" resultMap="recordResultMap">
        SELECT id,
            title,
            release_date,
            artist_id,
            label_id
        FROM record
        WHERE id = #{id}
    </select>
</mapper>
  • Record.java
package org.kodejava.mybatis.support;

import java.io.Serializable;
import java.util.Date;

public class Record implements Serializable {
    private Long id;
    private String title;
    private Date releaseDate;
    private Long artistId;
    private Long labelId;

    // Getters & Setters

    @Override
    public String toString() {
        return "Record{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", releaseDate=" + releaseDate +
                ", artistId=" + artistId +
                ", labelId=" + labelId +
                '}';
    }
}

The directory structure of the code above is:

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

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.13</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.1.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central