當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring集成Mybatis配置映射文件方法详解
生活随笔
收集整理的這篇文章主要介紹了
Spring集成Mybatis配置映射文件方法详解
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Spring ORM模塊集成Mybatis使用到了mybatis-spring,在配置mybatis映射文件的時(shí)候,一般不直接在Mybatis的配置文件里進(jìn)行配置,而會(huì)在Spring的配置文件里使用MapperScannerConfigurer來配置。MapperScannerConfigurer會(huì)自動(dòng)掃描basePackage指定的包,找到映射接口類和映射XML文件,并進(jìn)行注入。
Spring的配置文件applicationContext.xml內(nèi)容如下:
<!-- 掃描 mappers 自動(dòng)配置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.guowei.maven.framework.dao" /> </bean> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"><property name="locations"><list><value>classpath:mysqldb.properties</value></list></property></bean><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="ignoreResourceNotFound" value="false" /><property name="properties" ref="configProperties" /></bean><bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"><property name="driverClassName" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" /></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--dataSource屬性指定要用到的連接池--><property name="dataSource" ref="dataSource" /><!--configLocation屬性指定mybatis的核心配置文件--><property name="configLocation" value="mybatisconf.xml" /></bean>
但是,進(jìn)行這個(gè)配置的前提條件是:映射接口類文件(.java)和映射XML文件(.xml)需要放在相同的包下,比如:com.guowei.test.mapper。
如果Mybatis映射XML文件和映射接口文件不放在同一個(gè)包下,那就還需要在上面的基礎(chǔ)上,手動(dòng)配置SqlSessionFactoryBean的mapperLocations屬性,如下所示:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--dataSource屬性指定要用到的連接池--><property name="dataSource" ref="dataSource" /><!--configLocation屬性指定mybatis的核心配置文件--><property name="configLocation" value="mybatisconf.xml" /><!--mapperLocations屬性指定mybatis的映射文件--><property name="mapperLocations" value="classpath*:com/guowei/maven/framework/**/*.xml" /> </bean>
需要添加一個(gè)mapperLocations屬性,指定加載xml文件的路徑。
classpath:表示在classes目錄中查找;
*:通配符表示所有文件;
**:表示所有目錄下;
參考Mybatis官網(wǎng)說明如下:http://mybatis.github.io/spring/factorybean.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的Spring集成Mybatis配置映射文件方法详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 乌龟肉的功效与作用、禁忌和食用方法
- 下一篇: 鸭心的功效与作用、禁忌和食用方法