Mapper 編寫有哪幾種方式?

第一種:接口實現類繼承 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 接口:

48 頁 共 485 頁第 49 頁 共 485 頁

一、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 的實現對象。

Java Program!
相關文章
相關標籤/搜索