【踩坑记录】SpringBoot整合Mybatis常见问题

本文解决SpringBoot项目中MyBatis整合时常见的两大问题:Mapper类autowired失败和BindingException错误。提供配置类和配置文件两种解决方案,确保Mapper接口和XML映射正确绑定。
摘要由CSDN通过智能技术生成

问题一:Mapper类 autowired失败

原因:扫描mapper包没有配置或配置不正确

解决:

方案一:

1. 启动类加@MapperScan("mapperPackagePath")

方案二:

增加配置类: 

package com.yx.readingwebsite.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  MapperScannerConfigurer  配置DAO层
 */


@Configuration
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
        msc.setBasePackage("com.yx.readingwebsite.mapper");
        return msc;
    }
}

问题二:Mapper扫描成功后,继续报错,org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

原因:xml的mapper SQL 和 Mapper接口没有绑定

解决:

方案一:全局配置文件application.yml增加mybatis配置【xml mapper包在resource目录下】

mybatis:
  mapper-locations: classpath:mapper/*.xml

方案二:增加配置类

package com.yx.readingwebsite.config;

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.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * 配置MyBatis,引入数据源,sqlSessionFactory,sqlSessionTemplate,事务管理器
 */

@Configuration  //配置类
@EnableTransactionManagement //允许使用事务管理器
public class MyBatisModelConfig implements TransactionManagementConfigurer {

    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource); //设置数据源
        ssfb.setTypeAliasesPackage("com.yx.readingwebsite.model");   //设置扫描模型包【po】
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                    .getResources("classpath:mapper/*.xml");
            ssfb.setMapperLocations(resources);
            return ssfb.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Bean   //获得Session 模板,从而获得Session
    public SqlSessionTemplate getSqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Override   //事务管理器
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

需要注意的是,xml版的mybatis一定要在sqlSessionFactory中指定mapperLocations,即下图

总结:

两种配置方案。方案一,使用配置类;方案二,使用配置文件。完整配置如下:

方案一:配置类

package com.yx.readingwebsite.config;

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.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * 配置MyBatis,引入数据源,sqlSessionFactory,sqlSessionTemplate,事务管理器
 */

@Configuration  //配置类
@EnableTransactionManagement //允许使用事务管理器
public class MyBatisModelConfig implements TransactionManagementConfigurer {

    @Autowired
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource); //设置数据源
        ssfb.setTypeAliasesPackage("com.yx.readingwebsite.model");   //设置扫描模型包【po】
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver()
                    .getResources("classpath:mapper/*.xml");
            ssfb.setMapperLocations(resources);
            return ssfb.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Bean   //获得Session 模板,从而获得Session
    public SqlSessionTemplate getSqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Override   //事务管理器
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
package com.yx.readingwebsite.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  MapperScannerConfigurer  配置DAO层
 */


@Configuration
@AutoConfigureAfter(MyBatisModelConfig.class)
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
        msc.setBasePackage("com.yx.readingwebsite.mapper");
        return msc;
    }
}

方案二:配置文件 application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/readingWebsite?useUnicode=true&characterEncoding=utf-8
    username:
    password:
    driver-class-name: com.mysql.jdbc.Driver
    max-active: 100
    max-idle: 10
    max-wait: 10000
    default-auto-commit: false
    time-between-eviction-runs-millis: 30000
    min-evictable-idle-time-millis: 30000
    test-while-idle: true
    test-on-borrow: true
    test-on-return: true
    validation-query: SELECT 1

mybatis:
  mapper-locations: classpath:mapper/*.xml
package com.yx.readingwebsite;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.yx.readingwebsite")
public class ReadingWebsiteApplication {

    public static void main(String[] args) {
        SpringApplication.run(ReadingWebsiteApplication.class, args);
    }

}

借鉴各位大佬:

模块化开发SpringBoot整合MyBatis时Mapper.xml映射问题

springboot启动扫描不到dao层接口

spring boot 整合mybatis org.apache.ibatis.binding.BindingException: Invalid bound statement(not found)

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)异常处理

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name

spring boot+mybatis整合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值