SpringBoot学习笔记之mybatis分页插件集成

来源:互联网 发布:日本人茶点的知乎 编辑:程序博客网 时间:2024/05/16 11:40
Springboot Mybatis 分页使用
1)、引入依赖包
<!-- 整合mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.1</version>
</dependency>

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你会发现,只有两行主要的代码,如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.vk.liyj.mapper.CountryMapper">
</mapper>
mapper虽然只有短短的几行代码,但是却同样实现了CRUD等基本功能,请看service类代码:
@Service
public class CountryService {

@Autowired
private CountryMapper countryMapper;

public List<Country> 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


原创粉丝点击