MyBatis-Spring-Boot-Starter简要说明

1.MyBatis-Spring-Boot-Starter

MyBatis-Spring-Boot-Starter依赖将会提供如下

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

使用了该Starter之后,只需要定义一个DataSource即可(application.properties或application.yml中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

2.src\main\resources\application.yml

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/bootdo?useUnicode=true&characterEncoding=utf8
    username: root
    password: root
    initialSize: 3
    maxActive: 100
    minIdle: 10
    maxWait: 50000
  profiles:
    #dev(info) or prod(error)
    active: prod
    
  jackson:
    time-zone: GMT+8
    date-format: yyyy-MM-dd HH:mm:ss
    
  servlet:
     multipart:
        enabled: true
        max-file-size: 50Mb
        max-request-size: 300Mb

#配置MyBatis
mybatis:
  type-aliases-package: com.xxx.spring.mysqles.domain
  mapper-locations: classpath:mybatis/*Mapper.xml


3.Springboot配置原理来源Spring 配置

最常用的应该是 Mapper 动态代理开发,但是动态代理配置也有两种,一般使用第二种,本人也是使用第二种。如果第二种 首先有几点要确定。

  • *Mapper.java 和 *Mapper.xml 命名是否一致
  • 是否在一个包下,扫描能不能扫到 .xml或者将 *Mapper.xml 放在 resources 下。
  • *Mapper.xml 的 namespace 配置是否准确,接口方法名是否准确。
<!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <!-- 配置Mapper接口 -->
    <property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper" />
    <!-- 配置sqlSessionFactory -->
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
    <!-- Mapper动态代理开发 开发方式2   扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.guozh.bitbooks.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

问题说明

启动springboot中出现org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题,可参考

  • 将 *Mapper.xml 复制一份到 resources 下,记得修改 mybatis 配置文件的路径。
  • 在 pom.xml 中配置资源代码

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值