spring mysql 注解_SpringBoots基于Mybatis注解版(无xml)简单操作mysql含分页

创建数据库和表单

我这里直接用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);

}

}

是不是很简单呢~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值