Spring与Mybatis整合

一 概述

1.整合的目的

将Mapper映射器的创建任务交给Spring容器。

二 具体实现

1.创建sqlSessionFactory:

<bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource"ref="c3p0" />
       <property name="configLocation"value="classpath:MybatisConfiguration.xml" />
</bean>

2.创建Mapper:

⑴分散创建(逐个为Dao创建Mapper)

<bean id="dao"class="org.mybatis.spring.mapper.MapperFactoryBean">
       <property name="mapperInterface"value="com.spring_mybatis.dao.IStudentDao" />
       <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

⑵集中创建(为指定包下的所有Dao创建Mapper)

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage"value="com.spring_mybatis.dao;xxxxxxxxxxx" />
</bean>

①条件:

条件一:如果映射文件采用扫描包的方式加载,那么映射文件名必须为Dao的简单类名,与Dao位于同一包中。采用路径加载,映射文件名没有特殊要求。

条件二:MapperScannerConfigurer根据类别自动加载sqlSessionFactory,如果存在多个,可以通过名称指定:

<property name="sqlSessionFactoryName"ref="sqlSessionFactory"/>

②Mapper的id:

Dao的简单类名前两个字母均大写:id为简单类名,比如IStudentDao对应的Mapper的id为IStudentDao。

Dao的简单类名第一个字母大写,第二个字母小写开头:id为首字母小写后的简单类名,比如StudentDao

对应的Mapper的id为studentDao。

生成Mapper id的过程:

首先取简单类名,首字母小写,接着判断第二个字符是否大写,如果大写,id采用简单类名,小写则采用简单类名首字母小写后的形式。

原文地址:https://www.cnblogs.com/tonghun/p/6914557.html