- 引入Mybatis提供的mybatis-spring整合包,具体pom.xml配置如下:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
- mybatis-spring类包提供了一个SqlSessionFactoryBean,以便通过Spring风格创建Mybatis的SqlSessionFactory,applicationContext-mybatis.xml此处配置如下:
p:dataSource-ref指定依赖的数据源;p:mapperLocations指定映射文件路径;p:typeAliasesPackage指定实体类所在包路径<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:mapperLocations="classpath:com/smart/domain/mybatis/*.xml" p:typeAliasesPackage="classpath:com.smart.domain"/>
- mybatis提供了一个转换器MapperScannerConfigurer,可以将映射接口直接转换为spring容器中的bean,实现在service中注入映射接口的bean,applicationContext-mybatis.xml此处配置如下:
转换器将扫描basePackage指定包路径下的所有接口类,如果它们在SQL映射文件中定义过,则将它们动态定义为一个Spring Bean。<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:sqlSessionFactory-ref="sqlSessionFactory" p:basePackage="com.smart.dao.mybatis"/>
- applicationContext-mybatis.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:component-scan base-package="com.smart.dao.mybatis"/> <context:component-scan base-package="com.smart.service.mybatis"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/sampledb" p:username="root" p:password="123456"/> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:mapperLocations="classpath:com/smart/domain/mybatis/*.xml" p:typeAliasesPackage="classpath:com.smart.domain"/> <bean class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:sqlSessionFactory-ref="sqlSessionFactory" p:basePackage="com.smart.dao.mybatis"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
Spring整合Mybatis
最新推荐文章于 2024-09-30 10:53:04 发布