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.example.mybatis.annotation;

import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.kodejava.example.mybatis.domain.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);
}

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 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 read the configuration file using a org.apache.ibatis.io.Resources class. This information the passes as the argument of the build() method of the SqlSessionFactoryBuilder class. The build() method return an SqlSessionFactory object.

package org.kodejava.example.mybatis;

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

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.
        //
        String res = "org/kodejava/example/mybatis/Configuration.xml";
        Reader reader = Resources.getResourceAsReader(res);

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

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"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="record" type="org.kodejava.example.mybatis.domain.Record"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/mediadb"/>
                <property name="username" value="root"/>
                <property name="password" value="welcome"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/kodejava/example/mybatis/persistence/RecordMapper.xml"/>
    </mappers>
</configuration>