1.数据库表设计
CREATE DATABASE `springbootlearn`;
CREATE TABLE `student` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '姓名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `springbootlearn`.`students` (`id`, `name`) VALUES ('1', '小明');
INSERT INTO `springbootlearn`.`students` (`id`, `name`) VALUES ('2', '小花');
2.数据配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springbootlearn
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.实体层
package com.leo.springbootdemo;
/**
* 学生实体类
*/
public class Student {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
4.Mapper层
package com.leo.springbootdemo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
/**
* 学生Mapper
*/
@Mapper
@Repository
public interface StudentMapper {
@Select("select * from student where id = #{id}")
Student findById(Integer id);
}
5.service层
package com.leo.springbootdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 学生Service
*/
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public Student findStudent(Integer id) {
return studentMapper.findById(id);
}
}
6.controller层
package com.leo.springbootdemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping({"/student"})
public String student(@RequestParam Integer id) {
Student student = studentService.findStudent(id);
return student.toString();
}
}
7.执行