1.spring-mabatis.xml文件,主要是完成 dao層和pojo的自動(dòng)掃描裝配。
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動(dòng)掃描 -->
<context:component-scan base-package="com.df.test" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<!--或者這樣 引入配置文件 -->
<!-- <context:property-placeholder location="classpath:jdbc.properties"/> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化連接大小 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 連接池最大數(shù)量 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 連接池最大空閑 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 連接池最小空閑 -->
<property name="minIdle" value="${minIdle}"/>
<!-- 獲取連接最大等待時(shí)間 -->
<property name="maxWait" value="${maxWait}"/>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動(dòng)掃描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/df/test/mapping/*.xml"/>
</bean>
<!-- DAO接口所在包名,Spring會(huì)自動(dòng)查找其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.df.test.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
2.在此之前,我們要新建配置文件jdbc.properties,用來保存數(shù)據(jù)庫鏈接的相關(guān)信息,如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb
username=root
password=123456
#初始定義連接數(shù)
initialSize=0
#定義最大連接數(shù)
maxActive=20
#定義最大空閑
maxIdle=20
#定義最小空閑
minIdle=1
#定義最長等待時(shí)間
maxWait=60000