网上爬坑一上午 很多没说明到位 分享下自己解决过程.
有可能出错地点:
1.spring boot 使用 @Configuration 注解 java类 配置方式 没设置上插件 interceptor
2.没设置数据库方言 DialectType
3.引入了多个分页插件
4.代码里面重复实例化了多个page
@Configuration
@MapperScan("com.**.mapper")
@EnableTransactionManagement
public class MybatisDataSourceConfig {
private static final Logger log = LoggerFactory.getLogger(MybatisDataSourceConfig.class);
private static final String MAPPER_LOCATION = "classpath*:mybatis/**/*.xml";
@Value("${mybatis-plus.global-config.dbColumnUnderline}")
private Boolean dbColumnUnderline;
@Autowired
@Qualifier("mybatisDataSource")
private DataSource mybatisDataSource;
@Bean(name = "mybatisTransactionManager")
public DataSourceTransactionManager masterTransactionManager() {
return new DataSourceTransactionManager(mybatisDataSource);
}
@Bean(name = "mybatisSessionFactory")
public SqlSessionFactory mybatisSessionFactory() throws Exception {
//解决查询返回结果含null没有对应字段值问题
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setCallSettersOnNulls(true);
//配置slq打印日志
configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
//峰驼转换
configuration.setMapUnderscoreToCamelCase(dbColumnUnderline);
//注意把SqlSessionFactory 换成mybitaisPlus的 否则使用自带方法会报错
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(mybatisDataSource);
//mybatis对应spring boot环境的配置
sessionFactory.setVfs(SpringBootVFS.class);
//xml扫描路径
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MybatisDataSourceConfig.MAPPER_LOCATION));
//配置实体包路径
sessionFactory.setTypeAliasesPackage("com.**.entity");
//配置自定义类型转换 类包路径
sessionFactory.setTypeHandlersPackage("com.**.convert");
//添加分页插件 注意要添加到插件很多没说明这一步
Interceptor[] interceptor = {paginationInterceptor()};
sessionFactory.setPlugins(interceptor);
sessionFactory.setConfiguration(configuration);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(mybatisSessionFactory());
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setDialectType("mysql");
// paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
return paginationInterceptor;
}
成功调用后sql 语句会添加 分页部分