一.所需材料
以 spring boot集成mybatis(注解模式)文為基礎,在此基礎上引入mybatis-plus.
配置文件:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
二.項目目錄(略)
三.項目代碼
@Mapper public interface UserMapper extends BaseMapper<UserEntity> { }
@Service public class UserService { @Autowired private UserMapper userMapper; public UserEntity getOne(String x) { return userMapper.selectById(x); } }
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/get1") public UserEntity getOne(String id) { return userService.getOne(id); } }
以上代碼正常運行,但是service中會報如下警告:
Could not autowire. No beans of 'UserMapper' type found. less... (Ctrl+F1) Inspection info:Checks autowiring problems in a bean class.
參考:https://blog.csdn.net/qq_39039017/article/details/84143109
修改代碼為:
@Repository public interface UserMapper extends BaseMapper<UserEntity> { }
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Repository; @SpringBootApplication @MapperScan(basePackages = "***.com.mybatis14",annotationClass = Repository.class) public class Mybatis14Application { public static void main(String[] args) { SpringApplication.run(Mybatis14Application.class, args); } }
或者采用以下方式(參考:https://blog.csdn.net/Xu_JL1997/article/details/90934359):
@Mapper @Repository public interface UserMapper extends BaseMapper<UserEntity> { }
@SpringBootApplication public class Mybatis14Application { public static void main(String[] args) { SpringApplication.run(Mybatis14Application.class, args); } }
總結:一定要用@Mapper或者@MapperScan,沒有的話,mybatis無法找到mapper,無法生成具體業務代碼。而@Repository可有可無,如果沒有,開發環境會報警告,但不影響運行。加上后則警告消失。
四.運行結果
輸入調用地址:http://localhost:8080/user/get1?id=1
返回結果:

