好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Dao层@Repository与@Mapper的使用

Spring Dao层@Repository与@Mapper

使用注解的方式开发Dao层的时候,常常会混淆这两个注解,不知道怎么添加,这里做个记录。

1、@Mapper

@Mapper 是 Mybatis 的注解,和 Spring 没有关系,@Repository 是 Spring 的注解,用于声明一个 Bean。(重要)

使用 Mybatis 有 XML 文件或者注解的两种使用方式,如果是使用 XML 文件的方式,我们需要在配置文件中指定 XML 的位置,这里只研究注解开发的方式。

在 Spring 程序中,Mybatis 需要找到对应的 mapper,在编译的时候动态生成代理类,实现数据库查询功能,所以我们需要在接口上添加 @Mapper 注解。

?

1

2

3

4

@Mapper

public interface UserDao {

     ...

}

但是,仅仅使用@Mapper注解,我们会发现,在其他变量中依赖注入,IDEA 会提示错误,但是不影响运行(亲测~)。因为我们没有显式标注这是一个 Bean,IDEA 认为运行的时候会找不到实例注入,所以提示我们错误。如下图,会有红色波浪线。

尽管这个错误提示并不影响运行,但是看起来很不舒服,所以我们可以在对应的接口上添加 bean 的声明,如下:

?

1

2

3

4

5

6

7

8

@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;

}

2、@Repository

正如上面说的,@Repository 用于声明 dao 层的 bean,如果我们要真正地使用 @Repository 来进行开发,那是基于代码的开发,简单来说就是手写 JDBC。

和 @Service、@Controller 一样,我们将 @Repository 添加到对应的实现类上,如下:

?

1

2

3

4

5

6

7

8

9

@Repository

public class UserDaoImpl implements UserDao{

    

     @Override

     public int insertUser(){

         JdbcTemplate template = new JdbcTemplate();

         ...

     }

}

3、其他扫描手段

基于注解的开发也有其他手段帮助 Mybatis 找到 mapper,那就是 @MapperScan 注解,可以在启动类上添加该注解,自动扫描包路径下的所有接口。

?

1

2

3

4

5

6

7

@SpringBootApplication

@MapperScan ( "com.scut.thunderlearn.dao" )

public class UserEurekaClientApplication {

     public static void main(String[] args) {

         SpringApplication.run(UserEurekaClientApplication. class , args);

     }

}

使用这种方法,接口上不用添加任何注解。

4、小结

@Mapper :一定要有,否则 Mybatis 找不到 mapper。 @Repository :可有可无,可以消去依赖注入的报错信息。 @MapperScan :可以替代 @Mapper。

@Mapper和@Repository的区别

1、相同点

@Mapper和@Repository都是作用在dao层接口,使得其生成代理对象bean,交给spring 容器管理

对于mybatis来说,都可以不用写mapper.xml文件

2、不同点

@Mapper 不需要配置扫描地址,可以单独使用,如果有多个mapper文件的话,可以在项目启动类中加入@MapperScan([mapper文件所在包]),这样就不需要每个mapper文件都加@Mapper注解了 @Repository 不可以单独使用,否则会报如下错误

 Field userMapper in com.liu.service.UserServiceImpl required a bean of type 'com.liu.mapper.UserMapper' that could not be found.

找不到bean,这是因为项目启动的时候没有去扫描使用@Repository注解的文件,所以使用@Repository需要配置扫描地址

但在idea中,使用@Repository可以消除在业务层中注入mapper对象时的错误,如下图所示

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/Xu_JL1997/article/details/90934359

查看更多关于Spring Dao层@Repository与@Mapper的使用的详细内容...

  阅读:23次