#SpringBoot 整合使用mybatis及分页插件
org.springframework.boot
spring-boot-starter-parent
2.0.5.RELEASE
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-web
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
//@Mapper
public interface DeptMapper {
@Select("SELECT * FROM DEPT WHERE NAME = #{name}")
Dept findByName(@Param("name") String name);
@Insert("INSERT INTO DEPT(ID, NAME) VALUES(#{id}, #{name})")
int insert(@Param("id") int id, @Param("name") String name);
}
@SpringBootApplication
@MapperScan("com.rp.springboot.dao")
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
public class Dept {
private int id;
private String name;
//get set
...
}
pageHelper
PageHelper 是一款好用的开源免费的 Mybatis 第三方物理分页插件
物理分页
支持常见的 12 种数据库。Oracle,MySql,MariaDB,SQLite,DB2,PostgreSQL,SqlServer 等
支持多种分页方式
支持常见的 RowBounds(PageRowBounds),PageHelper.startPage 方法调用,Mapper 接口参数调用
在上述的pom文件中添加pageHelper依赖:
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.5
org.apache.commons
commons-lang3
3.7
配置文件中新增 pageHelper 的配置:
logging.level.com.rp.springboot.dao=DEBUG
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
pagehelper.page-size-zero=true
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
@Override
public Dept findByName(String name) {
return deptMapper.findByName(name);
}
@Override
public int insert(int id, String name) {
return deptMapper.insert(id,name);
}
@Override
public PageInfo getDeptList(int pageNum,int pageSize) {
// 开启分页插件,放在查询语句上面
PageHelper.startPage(pageNum,pageSize);
List all = deptMapper.findAll();
// 封装分页之后的数据
PageInfo info = new PageInfo(all);
return info;
}
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/getdept/{name}")
public Dept getDeptByName(@PathVariable("name")String name){
Dept byName = deptService.findByName(name);
return byName;
}
@GetMapping("/insert/{id}/{name}")
public boolean insert(@PathVariable("id") int id,@PathVariable("name")String name){
int insert = deptService.insert(id, name);
return insert>=1;
}
@GetMapping("/getall/{pageNum}/{pageSize}")
public PageInfo getAll(@PathVariable("pageNum") int pageNum,@PathVariable("pageSize") int pageSize){
return deptService.getDeptList(pageNum,pageSize);
}
}
源码地址: https://github.com/ruiace/springboot-mybatis.git