1

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

MyBatisPlusConfig.java

@Configuration
@MapperScan("com.qinhaoran.mpdemo.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQL_SERVER));
        return interceptor;
    }

}

application.yml

# 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;
    }

}

秦浩然
3 声望0 粉丝