The use of @ Mapper and @ MapperScan in mybatis annotations
- 2021-11-24 01:32:43
- OfStack
mybatis annotations @ Mapper and @ MapperScan
When using the Mybatis persistence layer framework to manipulate the database, we can use the @ Mapper annotation and the @ MapperScan annotation to hand over the Mapper interface class to Sprinig for management.
Mode 1: Use @ Mapper annotations
Advantages: finer granularity
Disadvantages: Adding @ Mapper annotation in Mapper interface class directly, it is necessary to add @ Mapper annotation in every mapper interface class, which is cumbersome
Mode 2: Use @ MapperScan annotations
With @ MapperScan, you can specify the packet path of the Mapper interface class to be scanned
@SpringBootApplication
@MapperScan("com.erayt.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
You can use * as a wildcard in the path to match the package name
@SpringBootApplication
@MapperScan("com.erayt.*.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
You can also scan multiple packages using @ MapperScan annotations
@SpringBootApplication
@MapperScan("com.erayt.mapperFirst","com.erayt.mapperSecond")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Difference and understanding between @ MapperScan and @ Mapper
Action
Scan the Dao layer in the project, inject dao interface class into Spring, and let other classes refer to it;
@Mapper
In the dao interface class, add this annotation; The trouble is that every dao interface class must add this annotation;
@MapperScan
You can specify the path of the dao interface class to be scanned, and you can add this annotation to the startup class instead of @ Mapper annotation. (You don't need to add @ Mapper annotation to all dao interface classes in this module.)
Scan 1 packet
@MapperScan("com.demo.mapper")
Scanning the interface in the specified package
@MapperScan("com.demo.*.mapper")
: 1 * represents a level 1 package; For example, you can scan com. demo. aaa. mapper, but you cannot scan com. demo. aaa. bbb. mapper
@MapperScan("com.demo.**.mapper")
Two * for any package; For example, you can scan com. demo. aaa. mapper, or you can scan com. demo. aaa. bbb. mapper
Scan multiple packets
If the dao interface class is under a package or sub-package that the main program can scan:
@MapperScan({"com.kfit.demo","com.kfit.user"})
If not, you can configure it as follows:
@MapperScan({"com.kfit.*.mapper","org.kfit.*.mapper"})