springboot中使用mybatis实现动态sql及分页的详细流程
时间: 2024-03-27 07:39:31 浏览: 66
使用SpringBoot和MyBatis实现动态SQL和分页的详细流程如下:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
```
2. 配置数据源
在application.properties文件中配置数据源信息,例如:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
3. Mapper文件
在Mapper文件中编写动态SQL的语句,例如:
```xml
<select id="queryByCondition" parameterType="map" resultMap="BaseResultMap">
select * from user
<where>
<if test="name != null and name != ''">
and name like concat('%', #{name}, '%')
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
```
4. 接口
在接口中定义方法,例如:
```java
List<User> queryByCondition(Map<String, Object> paramMap);
```
5. Service层
在Service层中调用Mapper层的方法,例如:
```java
public List<User> queryByCondition(String name, Integer age, Integer pageNum, Integer pageSize) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("name", name);
paramMap.put("age", age);
PageHelper.startPage(pageNum, pageSize);
return userDao.queryByCondition(paramMap);
}
```
6. Controller层
在Controller层中调用Service层的方法,例如:
```java
@GetMapping("/queryByCondition")
public Result queryByCondition(String name, Integer age, Integer pageNum, Integer pageSize) {
List<User> userList = userService.queryByCondition(name, age, pageNum, pageSize);
PageInfo<User> pageInfo = new PageInfo<>(userList);
return Result.success(pageInfo);
}
```
至此,SpringBoot和MyBatis实现动态SQL和分页的流程已经介绍完毕。
阅读全文