@Mapper 与 @MapperScan 的区别

1、@Mapper

作用:用在接口类上,在编译之后会生成相应的接口实现类
位置:对应的某个接口类上面

@Mapper
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

如果想要每个接口都要变成实现类,那么需要在每个接口类上加上@Mapper注解,比较麻烦,解决这个问题用 @MapperScan

2、@MapperScan

作用:扫描指定包下所有的接口类,然后所有接口在编译之后都会生成相应的实现类
位置:是在SpringBoot启动类上面添加,

接口类

public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

EmployeeMapper.xml 省略…
mybatis 相关的全局配置 省略…

SpringBootApplication 启动类

@MapperScan("com.aop8.springboot.mapper")
@SpringBootApplication
public class SpringBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplication.class, args);
	}
}

添加 @MapperScan("com.aop8.springboot.mapper") 注解以后,扫描 com.aop8.springboot.mapper 包下面所有的接口类,在编译之后都会生成相应的实现类。

2.1、@MapperScan 扫描多个包

@MapperScan 也支持多个包的扫描。

@MapperScan({"com.aop8.emp.mapper","com.aop8.dep.mapper"})
@SpringBootApplication
public class SpringBootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootApplication.class, args);
	}
}

2.2、 @MapperScan 使用表达式,来扫描的包和其子包下面的类

@SpringBootApplication   
@MapperScan({"com.aop8.*.mapper","com.baidu.*.mapper"})   
public class SpringBootApplication {       
	public static void main(String[] args) {          
		SpringApplication.run(SpringBootApplication.class, args); 
    }
}

3、总结:

@Mapper 是对单个类的注解。是单个操作。

@MapperScan 是对整个包下的所有的接口类的注解。是批量的操作。

发布了297 篇原创文章 · 获赞 263 · 访问量 114万+

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/103273172