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


        // 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) {

     * Returns a DataSource object.
     * @return a DataSource.
    public static DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        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;

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

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

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

Maven Dependencies


Maven Central Maven Central Maven Central



  1. I followed your sample above and it went well, though of course I change some implementation that will fit on my needs. Thank you very much you’re such a great help


Leave a Reply

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