spring boot和mybatis集成分页插件
MyBatis提供了拦截器接口,我们可以实现自己的拦截器,将其作为一个plugin装入到SqlSessionFactory中。
首先要说的是,Spring在依赖注入bean的时候,会把所有实现MyBatis中Interceptor接口的所有类都注入到SqlSessionFactory中,作为plugin存在。既然如此,我们集成一个plugin便很简单了,只需要使用@Bean创建PageHelper对象即可。
1、添加pom依赖
com.github.pagehelper pagehelper 4.1.0
2、MyBatisConfiguration.java类配置
packagecom.example.mybatis;
importjava.util.Properties;
importjavax.sql.DataSource;
importorg.apache.ibatis.plugin.Interceptor;
importorg.apache.ibatis.session.SqlSessionFactory;
importorg.mybatis.spring.SqlSessionFactoryBean;
importorg.mybatis.spring.SqlSessionTemplate;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.jdbc.datasource.DataSourceTransactionManager;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
importorg.springframework.transaction.annotation.TransactionManagementConfigurer;
importcom.github.pagehelper.PageHelper;
@Configuration
//加上这个注解,使得支持事务
@EnableTransactionManagement
publicclassMyBatisConfigimplementsTransactionManagementConfigurer{
@Autowired
privateDataSourcedataSource;
@Override
publicPlatformTransactionManagerannotationDrivenTransactionManager(){
returnnewDataSourceTransactionManager(dataSource);
}
@Bean(name="sqlSessionFactory")
publicSqlSessionFactorysqlSessionFactoryBean(PageHelperpageHelper){
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();
bean.setDataSource(dataSource);
//自定义数据库配置的时候,需要将pageHelper的bean注入到Plugins中,如果采用系统默认的数据库配置,则只需要定义pageHelper的bean,会自动注入。
bean.setPlugins(newInterceptor[]{pageHelper});
try{
returnbean.getObject();
}catch(Exceptione){
e.printStackTrace();
thrownewRuntimeException(e);
}
}
@Bean
publicSqlSessionTemplatesqlSessionTemplate(SqlSessionFactorysqlSessionFactory){
returnnewSqlSessionTemplate(sqlSessionFactory);
}
@Bean
publicPageHelperpageHelper(){
PageHelperpageHelper=newPageHelper();
Propertiesp=newProperties();
p.setProperty("offsetAsPageNum","true");
p.setProperty("rowBoundsWithCount","true");
p.setProperty("reasonable","true");
p.setProperty("dialect","mysql");
pageHelper.setProperties(p);
returnpageHelper;
}
}
3、分页查询测试
@RequestMapping("/likename")
publicListlikeName(@RequestParamStringname){
PageHelper.startPage(1,1);
returnstuMapper.likeName(name);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。