Java如何在MyBatis中使用@Select注释?

在上一个示例中,如何创建MyBatis映射器?您已经了解了如何使用映射器从数据库获取记录。在该示例中,在查询器xml文件中定义了选择查询。对于相同的功能,MyBatis还提供了对选择查询使用注释的解决方案。

在此示例中,我们将使用@Select注释定义查询。为了映射查询结果,我们可以使用@ResultMap注释,其中传递给该注释的值是id我们在mapper xml文件中定义的结果映射。
让我们来看一个interface使用注释从数据库获取记录的映射器定义的示例:

package org.nhooo.example.mybatis.annotation;

import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.nhooo.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);
}

Maven依赖

<dependencies>
    <!--https://search.maven.org/remotecontent?filepath=org/mybatis/mybatis/3.5.0/mybatis-3.5.0.jar-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.0</version>
    </dependency>
</dependencies>

Maven中央