-
从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件(那个xml写的是真的蛋疼。。。)。很恶心的一个事实是源码中并没有对于这个注解的详细解释
-
在 Spring 程序中,Mybatis 需要找到对应的 mapper,在编译的时候动态生成代理类,实现数据库查询功能,所以我们需要在接口上添加 @Mapper 注解。
@Mapper
public interface UserDao {
…
}
但是,仅仅使用@Mapper注解,我们会发现,在其他变量中依赖注入,IDEA 会提示错误,但是不影响运行(亲测~)。因为我们没有显式标注这是一个 Bean,IDEA 认为运行的时候会找不到实例注入,所以提示我们错误。如下图,会有红色波浪线。
尽管这个错误提示并不影响运行,但是看起来很不舒服,所以我们可以在对应的接口上添加 bean 的声明,如下:
@Repository // 也可以使用@Component,效果都是一样的,只是为了声明为bean
@Mapper
public interface UserDao {
@Insert("insert into user(account, password, user_name) " +
"values(#{user.account}, #{user.password}, #{user.name})")
int insertUser(@Param("user") User user) throws RuntimeException;
}
-
基于注解的开发也有其他手段帮助 Mybatis 找到 mapper,那就是 @MapperScan 注解,可以在启动类上添加该注解,自动扫描包路径下的所有接口。
@SpringBootApplication
@MapperScan(“com.scut.thunderlearn.dao”)
public class UserEurekaClientApplication {public static void main(String[] args) { SpringApplication.run(UserEurekaClientApplication.class, args); }
}
但是感觉有些麻烦。
【转自】https://blog.csdn.net/Xu_JL1997/article/details/90934359utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control