mybatis测试pagehelper的代码
时间: 2023-07-10 19:11:18 浏览: 122
MyBatis的pagehelper
以下是使用 MyBatis 和 PageHelper 插件进行分页查询的示例代码:
首先,在 pom.xml 文件中添加以下依赖:
```xml
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- PageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
```
然后,在 MyBatis 的配置文件(比如 `mybatis-config.xml`)中配置 PageHelper 插件:
```xml
<configuration>
<!-- 其他配置 -->
<plugins>
<!-- PageHelper 插件 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
```
接下来,我们假设有一个 `UserMapper` 接口和对应的实现类 `UserMapperImpl`,其中定义了一个分页查询用户信息的方法 `listUsersByPage`:
```java
public interface UserMapper {
List<User> listUsersByPage(int pageNum, int pageSize);
}
public class UserMapperImpl implements UserMapper {
private final SqlSessionFactory sqlSessionFactory;
public UserMapperImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public List<User> listUsersByPage(int pageNum, int pageSize) {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
PageHelper.startPage(pageNum, pageSize);
return mapper.listUsers();
}
}
}
```
其中,`PageHelper.startPage(pageNum, pageSize)` 会自动拦截下一次查询,并在查询语句中添加 LIMIT 子句,实现分页查询。
最后,我们可以编写一个测试类 `UserMapperTest` 来验证分页查询的效果:
```java
public class UserMapperTest {
private static SqlSessionFactory sqlSessionFactory;
@BeforeClass
public static void setup() {
// 初始化 SqlSessionFactory
String resource = "mybatis-config.xml";
try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 初始化数据库
try (SqlSession sqlSession = sqlSessionFactory.openSession();
Statement statement = sqlSession.getConnection().createStatement()) {
statement.executeUpdate("DROP TABLE IF EXISTS users");
statement.executeUpdate("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(20), age INT)");
statement.executeUpdate("INSERT INTO users VALUES (1, 'Alice', 20), (2, 'Bob', 21), (3, 'Charlie', 22)");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Test
public void testListUsersByPage() {
UserMapper userMapper = new UserMapperImpl(sqlSessionFactory);
List<User> users1 = userMapper.listUsersByPage(1, 2);
List<User> users2 = userMapper.listUsersByPage(2, 2);
assertEquals(2, users1.size());
assertEquals(1, users2.size());
assertEquals("Alice", users1.get(0).getName());
assertEquals("Bob", users1.get(1).getName());
assertEquals("Charlie", users2.get(0).getName());
}
}
```
在测试中,我们先使用 `setup` 方法初始化数据库,然后调用 `listUsersByPage` 方法进行分页查询,并检查查询结果是否符合预期。
阅读全文