Spring Boot MyBatis注解:@MapperScan和@Mapper


最近參與公司的新項目架構搭建,在使用mybatis的注解時,和同時有了不同意見,同事認為使用@Mapper注解簡單明了,而我建議使用@MapperScan,直接將mapper所在的目錄掃描進去就行,而且@Mapper需要在每一個mapper上都添加,繁瑣。同事又說--我們可以用逆向工程自動生產entity,mapper,service時,將注解加上,很方便的,於是各執一詞。

下面是我整理的這兩種方法的比較:

  使用@Mapper注解

  為了讓DemoMapper能夠讓別的類進行引用,我們可以在DemMapper類上添加@Mapper注解:

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

 

  直接在Mapper類上面添加注解@Mapper,但是這種方式要求每一個mapper類都需要添加此注解,麻煩。

  使用@MapperScan注解

  通過使用@MapperScan可以指定要掃描的Mapper類的包的路徑,比如:

@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); 
    } 
}    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM