SpringBoot+Mybatis-Plus两种分页方法

首先配置mybatis-plus配置

package demo.biz.generator.config;

import java.util.Properties;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;

@EnableTransactionManagement
@Configuration
@MapperScan("demo.biz.generator.mapper")
public class MybatisPlusConfig {

	/**
	 * 分页插件
	 */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    
    /**
     * 打印 sql
     */
	@Bean
	public PerformanceInterceptor performanceInterceptor() {
		PerformanceInterceptor performanceInterceptor =new PerformanceInterceptor();
	    // 格式化sql语句
	    Properties properties =new Properties();
	    properties.setProperty("format", "false");
	    performanceInterceptor.setProperties(properties);
	    return performanceInterceptor;
	}

}

第一种方式,mybatis-plus原生QueryWrapper方式分页,这种方式比较简单,可以不用修改Mapper,适合简单的增删改查。

@RequestMapping(value = "/orgist1")//,method = RequestMethod.POST)
public Map orglist1() {

    Map map = new HashMap<>();

    QueryWrapper queryWrapper =  new QueryWrapper<>();
    queryWrapper.orderByDesc("id");

    Page page = new Page<>(1,5);  // 查询第1页,每页返回5条
    IPage iPage = oauthOrganizationMapper.selectPage(page,queryWrapper);
    System.out.println(iPage.getRecords().size());
    System.out.println(JSON.toJSONString(iPage));
    return map;
}

第二种方式,使用mapper文件的select注解,优点是可以方便的建立查询语句,可以联合多表查询。

Mapper文件

@Select("SELECT * FROM oauth_organization WHERE id < #{m.id} ORDER BY `id` DESC")
List selectpage(Map m, Page page);

Controller文件

@RequestMapping(value = "/orgist4")//,method = RequestMethod.POST)
public Map orglist4() {

    Map map = new HashMap<>();
    Map m = new HashMap<>();
    m.put("id",5);
    Page page = new Page<>(1,5);
    page.setRecords(oauthOrganizationMapper.selectpage(m,page));
    System.out.println(page.getRecords().size());
    System.out.println(JSON.toJSONString(page));
    return map;
}

你可能感兴趣的:(学习心得)