@Mapper注解干啥用的
时间: 2023-12-04 14:29:17 浏览: 130
@Mapper注解的作用是将一个DAO交给Spring管理,实现了接口与实现类的自动绑定。使用@Mapper注解后,编译时会生成相应的接口实现类。这样可以避免手动编写mapper映射文件,节省了开发人员的时间和精力。同时,@Mapper注解还可以自动为添加了该注解的接口生成一个实现类。这样可以简化代码的编写,并且提高了开发效率。
相关问题
@mapper注解的使用
@Mapper注解是MyBatis框架中的注解,用于标识一个接口是MyBatis的Mapper接口,为其生成代理对象。在使用时,需要先在MyBatis的配置文件中配置扫描Mapper接口的路径,然后在需要使用Mapper接口的地方注入Mapper接口的实例即可。
示例代码:
```
@Mapper
public interface UserMapper {
User selectUserById(int userId);
}
```
在以上示例中,@Mapper注解标识了UserMapper接口是一个MyBatis的Mapper接口,可以在需要使用UserMapper接口的地方注入UserMapper的实例,并调用其方法来实现与数据库的交互。
@Mapper注解原理
@Mapper 注解是 MyBatis 框架中的一个重要注解,用于标识一个接口类作为 MyBatis 的 Mapper 接口。它的原理是通过 MyBatis 的动态代理技术,在运行时自动生成 Mapper 接口的实现类。
具体来说,当一个接口上使用了 @Mapper 注解后,MyBatis 在启动时会扫描所有的 Mapper 接口,然后根据接口定义生成一个代理类的实例。在使用 Mapper 接口时,实际上是通过代理类来执行相应的 SQL 操作。
代理类的生成过程主要涉及两个核心组件:MapperProxyFactory 和 MapperProxy。MapperProxyFactory 是一个工厂类,用于生成 MapperProxy 实例。MapperProxy 是动态代理的实际实现类,它实现了 InvocationHandler 接口,用于处理方法调用。
在调用 Mapper 接口的方法时,MapperProxy 的 invoke 方法会被触发。该方法根据方法名和参数类型等信息,将对应的 SQL 语句封装成一个 MappedStatement 对象,并将其交给 SqlSession 进行执行。执行结果会通过反射机制返回给调用方。
总结起来,@Mapper 注解的原理是利用 MyBatis 的动态代理技术,在运行时自动生成 Mapper 接口的实现类,并通过代理类来执行对应的 SQL 操作。这样可以简化开发过程,使得开发者只需关注接口的定义,而无需手动编写 Mapper 接口的实现类。
阅读全文
相关推荐















