简单概述
mybatis与spring进行整合,通过spring管理SqlSessionFactory、mapper接口。
mybatis配置
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!—使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers -->
<mappers>
<package name="cn.ade.mybatis.mapper" />
</mappers>
</configuration>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--引入外部属性文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="url" value="${jdbc.jdbcUrl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="minIdle" value="5"/>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--
指定要扫描的包路径,如果要扫描多个包,中间使用半角逗号分隔
注意:如果使用扫描器,不需要在sqlMapConfig.xml中加载mapper,要将mapper.xml和mapper.java放在同一个目录且同名
-->
<property name="basePackage" value="cn.ade.mybatis.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
注意:
这里使用sqlSessionFactoryBeanName而不使用sqlSessionFactory,原因是因为MapperScannerConigurer在扫描mapper时需要注入 sqlSessionFactory。
如果使用<property name=“sqlSessionFactory” ref=“sqlSessionFactory”/> 会存在PropertyPlaceholderConfigurer还没来得及替换dataSource定义中的${jdbc.driver}等数据源变量就注入到了MapperScannerConigurer中,将导致数据库连接不上。
如果改为如下方式可以解决问题:
<property name=“sqlSessionFactoryBeanName” value=“sqlSessionFactory”/>