首先,我们要使用@Mapper和@MapperScan注解的话,我们首先需要在对应的项目里面导入相关的依赖或者jar包。
1 2 3 4 5
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency>
|
@Mapper注解
前言:从mybatis3.4.0开始加入了@Mapper注解,目的就是为了不再写mapper映射文件。
- 优点:粒度更细
- 缺点:直接在Mapper接口类中加@Mapper注解,需要在每一个mapper接口类中都需要添加@Mapper注解,较为繁琐
- 作用:在接口类上添加了@Mapper,在编译之后会生成相应的实现类
- 添加位置:接口类上面
- 注意:在这个接口类里面的方法不能重载,因为他们在XML里面的ID不能一样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Mapper public interface StudentMapper { List<Student> selectall(); int addstudent(Student student); int delstudent(Integer sid); int updatestudent(String sname,Integer sid); }
|
@MapperScan注解
上面刚刚讲述了@Mapper注解可以把接口要变成实现类,如果项目有几个接口,你肯定会在对应的接口上写@Mapper注解,但是如果有一百个,上千个,你还会愿意去写吗,这个时候我们就可以使用@MapperScan注解来解决我们的问题。
方式一:通过@MapperScan可以指定要扫描的Mapper接口类的包路径
1 2 3 4 5 6 7 8
| @MapperScan(basePackages = {"com.study.mapper"}) @SpringBootApplication public class DemocsApplication { public static void main(String[] args) { SpringApplication.run(DemocsApplication.class, args); } }
|
方式二:使用@MapperScan注解对多个包进行扫描
1 2 3 4 5 6 7 8
| @MapperScan(basePackages = {"com.study.mapper1","com.study.mapper2"}) @SpringBootApplication public class DemocsApplication { public static void main(String[] args) { SpringApplication.run(DemocsApplication.class, args); } }
|
方式三:这里的.*代表的是扫描study下面下面任何带有子包
1 2 3 4 5 6 7 8
| @MapperScan(basePackages {"com.study.*.mapper"}) @SpringBootApplication public class DemocsApplication { public static void main(String[] args) { SpringApplication.run(DemocsApplication.class, args); } }
|