MyBatis 与 Spring 的整合
1.在pom.xml文件中添加下列内容,导入相关的jar包。
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
2.Spring 管理SqlSessionFactory,在Spring IoC容器配置文件Context.xml中添加下列内容:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:com/kfcl/hps/information/dao/mapper/*.xml"/>
<property name="typeAliasesPackage" value="com.kfcl.hps.information.model"/>
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<property name="mapUnderscoreToCamelCase" value="true"></property>
</bean>
</property>
</bean>
其中,dataSource为Spring管理的的连接池对象,mapperLocations填写MyBatis映射文件的路径,这里与Spring整合使用自动扫描机制,会自动搜索该路径所有符合条件的映射文件并解析,typeAliasesPackage填写Model类的路径,主要是扫描类型别名,Model类使用注解方式为Model全限定类名设置别名。
3.Spring管理SqlSessionTemplate,在Spring IoC容器配置文件Context.xml中添加下列内容:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
4.为每个dao