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>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023