- 替换依赖
- 修改sqlSessionFactory bean
- 分页插件不生效问题记录
1.替换依赖:
将原来的mybatis整合springboot的依赖去掉,替换成mybatis-plus
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.7</version>
</dependency>
2.修改sqlSessionFactory bean
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {try {//mybatis升级mybatis-plus,需要替换MybatisSqlSessionFactoryBeanMybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();//SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();//原来mybatis的方式sqlSessionFactoryBean.setDataSource(dataSource);PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:/mapper/*.xml");org.springframework.core.io.Resource config = resolver.getResource("classpath:mybatis-config.xml");sqlSessionFactoryBean.setMapperLocations(resources);sqlSessionFactoryBean.setConfigLocation(config);return sqlSessionFactoryBean.getObject();} catch (Exception e) {logger.error("create sqlSessionFactoryBean error", e);throw new RuntimeException("create sqlSessionFactoryBean error");}
}
3.分页插件不生效问题
3.1配置分页插件:
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbTypereturn interceptor;}
}
3.2 使用分页方法
/*** 分页查询用户列表*/
public List<TUserInfo> selectUserListByPage(TUserInfo userInfo, Page<TUserInfo> page) {return baseMapper.selectPage(page, new QueryWrapper<>(userInfo)).getRecords();
}
但是他的sql打印并没有带limit,解决方案:手动设置插件
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPlusInterceptor mybatisPlusInterceptor) {try {//mybatis升级mybatis-plus,需要替换MybatisSqlSessionFactoryBeanMybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();//SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();//原来mybatis的方式sqlSessionFactoryBean.setDataSource(dataSource);PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:/mapper/*.xml");org.springframework.core.io.Resource config = resolver.getResource("classpath:mybatis-config.xml");sqlSessionFactoryBean.setMapperLocations(resources);sqlSessionFactoryBean.setConfigLocation(config);//分页未生效效,这里手动设置插件Interceptor[] plugins = {mybatisPlusInterceptor};sqlSessionFactoryBean.setPlugins(plugins);return sqlSessionFactoryBean.getObject();} catch (Exception e) {logger.error("create sqlSessionFactoryBean error", e);throw new RuntimeException("create sqlSessionFactoryBean error");}
}