创建数据库和表单
我这里直接用navica建了,注意将id设为主键,并且自动递增。
添加依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
//该插件为分页插件
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5
创建实体类
public class Student {
private int id;
private String name;
private int age;
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; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
创建Mapper
@Mapper
public interface studentDao {
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
@Select("SELECT * FROM student WHERE age = #{age}") //输入年龄查询
List get(int age);
@Select("SELECT * FROM student") //查询全部
Page getall();
@Insert("INSERT INTO student(name, age) VALUES (#{name}, #{age})")
@Options(keyProperty = "id", useGeneratedKeys = true) //设定id为主键且自增
void insert(Student student);
}
创建 Service类
@Service
public class UserService {
@Autowired
private studentDao studentDao;
public List showDao(int age) {
return studentDao.get(age);
}
public List showbypage(int page,int limit) {
PageHelper.startPage(page,limit); //分页核心语句
Page userlist = studentDao.getall();
return userlist;
}
public String insert(String name, int age) { //插入一条记录
Student student = new Student();
student.setName(name);
student.setAge(age);
studentDao.insert(student);
return "Insert ( \""+name+"\", age"+age+") OK!";
}
}
Controller
@RestController
public class studentController {
@Autowired
private UserService userService;
@PostMapping(value = "/show")
public Object show(@RequestParam("age") int age)
{
return userService.showDao(age);
}
@PostMapping(value = "/showbypage") //要传递2个参数,即当前页和每页显示的数据数量
public Object show(@RequestParam("page") int page, @RequestParam("limit") int limit)
{
return userService.showbypage(page,limit);
}
@PostMapping(value = "/insert")
public String show(@RequestParam("name") String name,@RequestParam("age") int age)
{
return userService.insert(name,age);
}
}
是不是很简单呢~~