第一种:接口实现类继承 SqlSessionDaoSupport:使用此种方法须要编写 spring
mapper 接口,mapper 接口实现类、mapper.xml 文件。 sql
一、在 sqlMapConfig.xml 中配置 mapper.xml 的位置 mybatis
<mappers> app
<mapper resource="mapper.xml 文件的地址" /> ide
<mapper resource="mapper.xml 文件的地址" /> this
</mappers> spa
一、定义 mapper 接口 xml
三、实现类集成 SqlSessionDaoSupport 对象
mapper 方法中能够 this.getSqlSession()进行数据增删改查。 继承
四、spring 配置
<bean id=" " class="mapper 接口的实现">
<property name="sqlSessionFactory"
ref="sqlSessionFactory"></property>
</bean>
第二种:使用 org.mybatis.spring.mapper.MapperFactoryBean:
一、在 sqlMapConfig.xml 中配置 mapper.xml 的位置,若是 mapper.xml 和
mappre 接口的名称相同且在同一个目录,这里能够不用配置
<mappers>
<mapper resource="mapper.xml 文件的地址" />
<mapper resource="mapper.xml 文件的地址" />
</mappers>
二、定义 mapper 接口:
一、mapper.xml 中的 namespace 为 mapper 接口的地址
二、mapper 接口中的方法名和 mapper.xml 中的定义的 statement 的 id 保持一
致
三、Spring 中定义
<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface"
value="mapper 接口地址" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
第三种:使用 mapper 扫描器:
一、mapper.xml 文件编写:
mapper.xml 中的 namespace 为 mapper 接口的地址;
mapper 接口中的方法名和 mapper.xml 中的定义的 statement 的 id 保持一致;
若是将 mapper.xml 和 mapper 接口的名称保持一致则不用在 sqlMapConfig.xml
中进行配置。
二、定义 mapper 接口:
注意 mapper.xml 的文件名和 mapper 的接口名称保持一致,且放在同一个目录
三、配置 mapper 扫描器:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="mapper 接口包地址
"></property>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory"/>
</bean>四、使用扫描器后从 spring 容器中获取 mapper 的实现对象。