乐趣区

关于mybatis-plus:MyBatisPlus-SQLServer-分页查询

SpringBoot 演示我的项目:

POM

<!-- MyBatis-Plus -->
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.4.3.4</version>
</dependency>
<!-- SQLServer 驱动 -->
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc4</artifactId>
    <version>4.0</version>
</dependency>

Config

# DataSource Config
spring:
  datasource:
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://127.0.0.1:1433;databaseName=my_db
    username: sa
    password: 123456

# Print SQL
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Model

@Data
@TableName("user")
public class User {
    private Long id;
    private String name;
}

Mapper

@Service
public interface UserMapper extends BaseMapper<User> {}

Test

@SpringBootTest
public class LessonTest {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试分页获取用户
     */
    @Test
    public void testPageUsers() {
        // 第 1 页,每页 10 条记录
        Page<User> page = new Page<>(1, 10);
        // 设置查问条件:依照用户名排序
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("Name");
        
        // 分页获取用户(可在控制台查看生成的 SQL)Page<User> users = userMapper.selectPage(page, wrapper);
        // 验证用户数应为 10
        assert users.size() == 10;}

}
退出移动版