144. Spring Boot MyBatis Upgrade - Annotation - Special: @MapperScan and @Mapper

 

【Video & Communication Platform】

à SpringBoot Video 

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à  SpringCloud video

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à Spring Boot source code 

https://gitee.com/happyangellxq520/spring-boot

à Spring Boot communication platform 

http://412887952-qq-com.iteye.com/blog/2321532

 

 

Origin of need:

       In the previous article, we defined the DemoMapper class, but did not define annotations like @Service or @Controller on this class, so why can it be managed by Spring ?

 

( 1 ) Method 1: Use @Mapper annotation

       In order for DemoMapper to be referenced by other classes, we can add the @Mapper annotation to the DemMapper class:

@Mapper
public interface DemoMapper {
    @Insert("insert into Demo(name) values(#{name})")
    @Options(keyProperty="id",keyColumn="id",useGeneratedKeys=true)
    public void save(Demo demo);
}

 

Add the annotation @Mapper directly on the Mapper class . This method requires each mapper class to add this annotation, which is troublesome.

 

( 2 ) Method 2: Use @MapperScan annotation

       By using @MapperScan you can specify the path to the package of the Mapper class to scan , for example:

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

 

或者:

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

 

       可以根据包的结构指定不同的表达式。

 

使用@MapperScan注解多个包

可以使用如下的方式指定多个包:

@SpringBootApplication
@MapperScan({"com.kfit.demo","com.kfit.user"})
public class App {
    public static void main(String[] args) {
       SpringApplication.run(App.class, args);
    }
}

 

       如果mapper类没有在Spring Boot主程序可以扫描的包或者子包下面,可以使用如下方式进行配置:

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

 

 

视频&交流平台

à SpringBoot网易云课堂视频

http://study.163.com/course/introduction.htm?courseId=1004329008

à Spring Boot交流平台

http://412887952-qq-com.iteye.com/blog/2321532

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326859394&siteId=291194637