例如,下面mapp接口文件中的方法使用@SelectProvider来注解,sql provider类UserSqlBuilder实现了org.apache.ibatis.builder.annotation.ProviderMethodResolver接口:
package com.thb.mapper;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;
import com.thb.model.User;
public interface UserMapper {
@SelectProvider(type = UserSqlBuilder.class)
User selectOneUserById(int id);
public static class UserSqlBuilder implements ProviderMethodResolver {
public static String selectOneUserById(final int id) {
return new SQL() {{
SELECT("id as id, user_name as userName, home_town as homeTown");
FROM("user");
WHERE("id = #{id}");
}}.toString();
}
}
}
对于ProviderMethodResolver接口,提供了默认实现函数resolveMethod(ProviderContext context)
:可以在ProviderMethodResolver实现类中自动匹配跟mapper接口中同名的方法。
例如,上面代码示例中,mapper接口中的方法定义,在SelectProvider注解的属性中,没有使用method属性指定方法,可以自动找到UserSqlBuilder中的同名方法selectOneUserById。因此,在这种情况下,@SelectProvider(type = UserSqlBuilder.class)
和@SelectProvider(type = UserSqlBuilder.class, method = "selectOneUserById")
是等价的:
@SelectProvider(type = UserSqlBuilder.class)
User selectOneUserById(int id);