【spring boot】mybatis啟動報錯:Consider defining a bean of type 'com.newhope.interview.dao.UserMapper' in your configuration. 【Mapper類不能被找到】@Mapper 和@MapperScan注解的區別


啟動報錯:

2018-05-16 17:22:58.161 ERROR 4080 --- Disconnected from the target VM, address: '127.0.0.1:50529', transport: 'socket'
[  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field huaYangAreaMapper in com.sxd.swapping.service.impl.HuaYangServiceImpl required a bean of type 'com.sxd.swapping.dao.mybatis.HuaYangAreaMapper' that could not be found.


Action:

Consider defining a bean of type 'com.sxd.swapping.dao.mybatis.HuaYangAreaMapper' in your configuration.

 

解決方案:

根據錯誤提示

Mybatis的 Mapper類不能被找到,所以需要通過注解標明這個類可以給spring 管理並且給其他類調用的。

 

下面有兩種方式提供:

方式1:使用@Mapper注解標注在Mapper類上

@Mapper
public interface HuaYangAreaMapper {

    @Select("SELECT * FROM hua_yang_area where uid = #{uid}")
    @Results({
            @Result(property = "areaName",column = "area_name",javaType = String.class),
            @Result(property = "areaPerson",column = "area_person",javaType = Long.class),
            @Result(property = "createId",column = "create_id",javaType = String.class)
    })
    HuaYangArea findOne(String uid);


}

 

 

方式2:使用@MapperScan("mapper類所在包位置")

@SpringBootApplication
@MapperScan("com.sxd.swapping.dao.mybatis")
public class SwappingApplication {

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

如果有多個包需要被掃描到,可以傳入字符串數組

@MapperScan({"com.sxd.swapping.dao.mybatis","com.sxd.swapping.dao.mapper"})

 

 

上面這兩種方式都可以使用。

====================================

至於@Mapper 和@MapperScan注解的區別,一個只需要在啟動類配置一次,一個是需要在每個mapper上進行配置

 


免責聲明!

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



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