-
创建数据库和表单
我这里直接用navica建了,注意将id设为主键,并且自动递增。 -
添加依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> //该插件为分页插件 <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>
-
创建实体类
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<Student> get(int age); @Select("SELECT * FROM student") //查询全部 Page<Student> 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<Student> showDao(int age) { return studentDao.get(age); } public List<Student> showbypage(int page,int limit) { PageHelper.startPage(page,limit); //分页核心语句 Page<Student> 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); } }
-
是不是很简单呢~~
SpringBoots基于Mybatis注解版(无xml)简单操作mysql含分页
猜你喜欢
转载自blog.csdn.net/qq_41850449/article/details/88790608
今日推荐
周排行