Sprngboot项目怎么整合mybatis和pagehelper
时间: 2023-04-07 16:01:22 浏览: 122
可以使用MyBatis的Spring Boot Starter和PageHelper的Spring Boot Starter来整合MyBatis和PageHelper。首先,在pom.xml文件中添加以下依赖项:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
然后,在application.properties文件中配置MyBatis和PageHelper:
```
mybatis.mapper-locations=classpath:mapper/*.xml
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
```
最后,在Spring Boot应用程序中使用@Mapper注释来标记MyBatis映射器接口,并在需要分页的方法中使用PageHelper.startPage方法来启用分页:
```
@Mapper
public interface UserMapper {
List<User> findAll();
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
void save(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void delete(@Param("id") Long id);
@Select("SELECT * FROM user")
List<User> findByPage();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
@Override
public User findById(Long id) {
return userMapper.findById(id);
}
@Override
public void save(User user) {
userMapper.save(user);
}
@Override
public void update(User user) {
userMapper.update(user);
}
@Override
public void delete(Long id) {
userMapper.delete(id);
}
@Override
public PageInfo<User> findByPage(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.findByPage();
return new PageInfo<>(userList);
}
}
```
以上就是整合MyBatis和PageHelper的步骤。
阅读全文