mybatis和spring的整合操作
阿新 • • 發佈:2019-01-13
1.最主要的是整合兩個配置檔案,將主要的配置資訊放入在spring的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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!--1.配置連線的資料來源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=round"></property> <property name="username" value="root"></property> <property name="password" value="jzbr"></property> </bean> <!-- 2.獲取sqlsessionfactorybean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 將資料來源對應的元件引入 --> <property name="dataSource" ref="dataSource"></property> <!-- 匯入mybatis的配置檔案 <property name="configLocation" value="classpath:mybatis-config.xml"/>--> <!-- 可以將介面的配置檔案放入當中 --> <!-- <property name="mapperLocations"> <list> <value>classpath:com/dao/**/*.xml</value> </list> </property> --> <!-- 配置類的別名 --> </bean> <!-- 3.獲取sqlsession物件 --> <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 注意:此處要以構造器的方式注入 <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> </bean> --> <!-- 4.載入service和dao元件 --> <!-- <bean id="userMapper" class="com.dao.userMapperImple"> <property name="sqlSessionTemplate" ref="sqlSession"></property> </bean> --> <!-- <bean id="userService" class="com.service.UserServiceImple"> <property name="userMapper" ref="userMapper"></property> </bean> --> <!-- 可以進行優化?獲取sqlsession這一步略顯複雜 可以實現將dao自動進行對映,同時引用sqlsessionfactorybean 這樣第3,4步不需要,此種方式會少寫一步 --> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.dao.UserMapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!-- mapper介面 要進行手工配置比較麻煩,設定自動掃描mapper介面 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dao"></property> </bean> <!--以配置的方式實現IOC,service到dao層的訪問 --> <context:component-scan base-package="com.service"></context:component-scan> </beans>