spring boot集成mybatis-plus(注解模式)

一.所需材料

以 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

返回结果:

 

posted @ 2020-11-16 10:50  Shapley  阅读(798)  评论(0编辑  收藏  举报