使用Spring Initializer快速构建
先去Spring Initializer官网 快速构建一个的springboot基础项目
配置选择
配置 | 选项 |
---|---|
Project | maven project |
language(语言) | java |
spring boot | 2.3.1, 默认推荐即可 |
Project Metadata | 自行填写 |
packaging | jar |
java | 8 |
添加依赖
- Spring Web
- JDBC Api
- MySql Driver
- Mybatis FrameWork
点击创建(CREATE), 下载项目
构建简单http服务
添加controller
@RestController
@RequestMapping("/hi")
public class HelloController {
@RequestMapping("/{name}")
public String hello(@PathVariable("name") String name) {
return "hello " + name + "! welcome!!!";
}
}
测试
运行访问 http://127.0.0.1:8080/hi/xiaodoubi, 发现运行ok, 能正常访问
hello xiaodoubi! welcome!!!
运行前, 注释掉pom.xml中关于数据库的库, jdbc, driver等依赖, 后面集成了数据库在打开
集成mybatis
依然使用我们之前的数据库,表, 打开上面注释掉的相关依赖
mybatis 生成器
使用mybatis generator生成xml, mapper以及实体类
User.java, UserMapper.xml, 生成详情见前面教程
添加UserController
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/{id}")
public User selectById(@PathVariable("id") Integer id) {
return userMapper.selectById(id);
}
}
配置application.yml
删掉applicaiton.properties, 新建application.yml(更简洁)
server:
port: 8080
# spring数据库连接, 仅为测试, 未使用数据库连接池配置
spring:
datasource:
name: test
url: jdbc:mysql://172.28.149.239:3306/test?useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis的mapping的xml文件
mybatis:
mapper-locations: classpath:mapping/*.xml
运行
运行Application, 发现报错
No qualifying bean of type 'top.itkaoti.mybatis.springbootmybatistest.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
报错原因:添加UserMaper注入是找不到bean, 因为mapper没有被spring扫描到,无法被spring管理
添加mapper包扫描, 让spring去管理这些mapper
@SpringBootApplication
@MapperScan({"top.itkaoti.mybatis.springbootmybatistest.mapper"})
public class SpringBootMybatisTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisTestApplication.class, args);
}
}
访问 http://127.0.0.1:8080/user/1
{"id":1,"name":"xiaodoubi","age":27,"sex":1}