MyBatis的Mapper注解

  • 从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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值