首页 > 代码库 > Spring Boot集成MyBatis与分页插件

Spring Boot集成MyBatis与分页插件

Maven依赖:

<dependency>    <groupId>com.github.pagehelper</groupId>    <artifactId>pagehelper</artifactId>    <version>4.1.6</version></dependency>

MybatisConfig.java:

import java.util.Properties;import javax.sql.DataSource;import org.apache.ibatis.plugin.Interceptor;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.SqlSessionTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.transaction.annotation.EnableTransactionManagement;import org.springframework.transaction.annotation.TransactionManagementConfigurer;import com.github.pagehelper.PageHelper;@Configuration  @EnableTransactionManagement  public class MyBatisConfig implements TransactionManagementConfigurer {        @Autowired    DataSource dataSource;            @Bean(name = "sqlSessionFactory")    public SqlSessionFactory sqlSessionFactoryBean() {        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        bean.setDataSource(dataSource);        // 分页插件        PageHelper pageHelper = new PageHelper();        Properties props = new Properties();        props.setProperty("reasonable", "true");        props.setProperty("supportMethodsArguments", "true");        props.setProperty("returnPageInfo", "check");        props.setProperty("params", "count=countSql");        pageHelper.setProperties(props);        // 添加插件        bean.setPlugins(new Interceptor[] { pageHelper });        try {            return bean.getObject();        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    @Bean    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {        return new SqlSessionTemplate(sqlSessionFactory);    }    @Bean    @Override    public PlatformTransactionManager annotationDrivenTransactionManager() {        return new DataSourceTransactionManager(dataSource);    }        }

PageHelper.startPage(pageNum,pageSize)方法调用后,后面必须有一个Mapper的查询方法,必须被消费掉。

List<Map> result=userMapper.getUser()

return new PageInfo(result)

当时知道数据类型时,可以进行强转。String s=JSON.toJSONString(json);JSONObject json=JSONObject.parentObject(String s)

还有遇到了postman无法使用的问题,因为开了绿豆vpn......

Spring Boot集成MyBatis与分页插件