Springboot Mybatis 分页使用
1)、引入依赖包
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
tk.mybatis
mapper-spring-boot-starter
1.1.4
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.1
2)、增加mybatis配置
#mybatis配置
mybatis.typeAliasesPackage=com.vk.liyj
#匹配mapper下的所有mapper.xml
#mybatis.mapperLocations=classpath:com/vk/liyj/mapper/*Mapper.xml
#匹配指定包下的所有mapper.xml
mybatis.mapperLocations=classpath*:com/vk/liyj/**/*Mapper.xml
#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=tk.mybatis.springboot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
3、相关的Country类的controller、model、service、mapper类开发
如果要使用分页查询功能,model类必须要继承BaseEntity类,BaseEntity中定义了分页相关的属性和表的主键;mapper接口必须要继承BaseMapper类,BaseMapper接口类内置了一整套通用的方法,查看mapper.xml你会发现,只有两行主要的代码,如下:
mapper虽然只有短短的几行代码,但是却同样实现了CRUD等基本功能,请看service类代码:
@Service
public class CountryService {
@Autowired
private CountryMapper countryMapper;
public List getAll(Country country) {
if (country.getPage() != null && country.getRows() != null) {
PageHelper.startPage(country.getPage(), country.getRows());
}
Example example = new Example(Country.class);
Example.Criteria criteria = example.createCriteria();
if (country.getCountryname() != null && country.getCountryname().length() > 0) {
criteria.andLike("countryname", "%" + country.getCountryname() + "%");
}
if (country.getCountrycode() != null && country.getCountrycode().length() > 0) {
criteria.andLike("countrycode", "%" + country.getCountrycode() + "%");
}
return countryMapper.selectByExample(example);
}
public Country getById(Integer id) {
return countryMapper.selectByPrimaryKey(id);
}
public void deleteById(Integer id) {
countryMapper.deleteByPrimaryKey(id);
}
public void save(Country country) {
if (country.getId() != null) {
countryMapper.updateByPrimaryKey(country);
} else {
countryMapper.insert(country);
}
}
}
4、在templates目录下添加freemarker模板getAll.ftl和view.ftl文件。启动SpringBootSampleApplication即可开始测试。
测试方法:
http://localhost:8080/web/countries/getAll
源码下载地址:http://download.csdn.net/download/liyuejin/9986140