参考答案
单纯使用 spring-context 和 spring-jdbc 集成 MyBatis。
配置步骤:
- 加载 spring-context、spring-jdbc、MyBatis、MyBatis-Spring 的 jar 包。
- spring 集成 MyBatis 的 xml 配置文件,配置 dataSource、sqlSessionFactory、Mapper 接口包扫描路径。
- Mapper 接口代理 bean 直接从 spring ioc 容器中获得使用即可。
最核心的是 spring 的配置文件:
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
">
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true" />
<bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
<!-- 基本属性 url、user、password -->
<property name="driver" value="${jdbc_driver}" />
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
</bean>
<!-- spring 和 Mybatis整合 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:constxiong/mapper/*.xml" />
</bean>
<!-- DAO接口所在包,配置自动扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="constxiong.mapper"/>
</bean>
</beans>
以上,是MyBatis面试题【Spring中如何配置MyBatis】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—
