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 record WHERE id = #{id}")
@ResultMap("recordResultMap")
Record getRecord(Long id);
}
Maven Dependencies
<dependencies>
<!-- https://search.maven.org/remotecontent?filepath=org/mybatis/mybatis/3.5.11/mybatis-3.5.11.jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.30/mysql-connector-java-8.0.30.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023