springboot整合mybatis-puls并实现分页功能非常简单,配置和依赖如下
依赖
<!-- 整合web的依赖,此依赖中包含mvc的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 快速操作实体类的依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-puls依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 如果mapper.xml文件在src目录下加入 -->
<resources>
<resource>
<directory>src/main/java</directory>
<filtering>false</filtering>
<includes>
<include>**/mapper/*.xml</include>
</includes>
</resource>
</resources>
yml配置
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/48topic?useUnicode=true&&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: root
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/hps/mapper/*.xml
分页配置
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
实体类的创建
@Data
@ToString
@TableName(value = "student") //表名
public class Student {
@TableId(type = IdType.AUTO) //主键
private Integer sid;
@TableField(value = "sname") //列名
private String sname;
@TableField(value = "sage")
private Integer sage;
@TableField(value = "ssex")
private String ssex;
}
启动类配置扫面mapper接口
@MapperScan("com.hps.dao")
@SpringBootApplication
public class DemoMybatisPulsApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMybatisPulsApplication.class, args);
}
}
service实现层完成查询分页
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public IPage getPageAllByUser(Integer pageNum,Integer pageSize) {
//分页处理,pageNum页,pageSize条数据
Page page = new Page(pageNum,pageSize);
return studentDao.findAll(page);
}
}
创建mapper接口
public interface StudentMapper extends BaseMapper<Student> {
IPage findAll(Page page);
}
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.hps.dao.StudentMapper">
<select id="findAll" resultType="com.hps.entity.Student">
SELECT `sid`,`sname`,`sage`,`ssex`
FROM `student`
</select>
</mapper>
此时咱们的springboot整合mybatis-puls及分页已经完成,可以进行测试验证。
如有问题欢迎指出