Spring Boot + Mybatis 完成数据查询
引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
mybatis-spring-boot-starter版本需要与spring boot 的版本一致(不同的mybatis的start对应的springboot的版本都是不完全一致的)
properties里进行数据库连接配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/imooc?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
数据库建表
create table students
(
id int auto_increment primary key,
name varchar(23) not null
);
insert into students (id, name) values (1, '小明');
insert into students (id, name) values (2, '小红');
新建实体类
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
新建Mapper对象操作数据库(这里是用的interface接口!!)
/**
* 新建Mapper对象操作数据库
*/
@Mapper
@Repository
public interface StudentMapper {
@Select("select * from students where id=#{id}")
Student findById(int id);
}
新建service类
/**
* 学生service
*/
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student findStudent(int id) {
return studentMapper.findById(id);
}
}
新建controller层
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping("/student")
public Map findStudent(@RequestParam int num) {
HashMap<Object, Object> result = new HashMap<>();
Student student = studentService.findStudent(num);
result.put("data", student);
result.put("msg", "Successful");
result.put("code", 0);
return result;
}
}
output
{
"msg": "Successful",
"code": 0,
"data": {
"id": 1,
"name": "小明"
}
}