【MyBatis】Mapper 编写的方式

第 一种:接口实现 类继承 SqlSessionDaoSupport :

使用此种方法需 要编写 mapper 接口, mapper 接口 实现类、mapper.xml 文件。

(1 )在 sqlMapConfig.xml 中配 置 mapper.xml 的位置

<mappers>

<mapper resource="mapper.xml 文件 的地 址" />

<mapper resource="mapper.xml 文件 的地 址" />

</mappers>

(2)定 义 mapper 接口

(3)实 现类集成 SqlSessionDaoSupport

mapper 方法 中可以 this.getSqlSession()进行 数据增删改查。

(4 )spring 配置

<bean id=" " class="mapper 接口 的实 现 ">

<property name="sqlSessionFactory"

ref="sqlSessionFactory"></property>

</bean>

第二种:使用 org.mybatis.spring.mapper.MapperFactoryBean :

(1 )在 sqlMapConfig.xml 中配 置 mapper.xml 的 位 置,如果 mapper.xml 和 mappre 接口的名称相同且 在同一个目录,这 里可以不用配置

<mappers>

<mapper resource="mapper.xml 文件 的地 址" />

<mapper resource="mapper.xml 文件 的地 址" />

</mappers>

(2)定 义 mapper 接口 :

(3)mapper.xml 中的 namespace 为 mapper 接口 的地 址

(4)mapper 接口 中的方法名和 mapper.xml 中的 定义的 statement 的 id 保持 一致

(5 )Spring 中定义

<bean id="" class="org.mybatis.spring.mapper.MapperFactoryBean"> 

<property name="mapperInterface" value="mapper 接口 地址" />

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

</bean>

第三种:使用 mapper 扫描器:

(1 )mapper.xml 文件编写:

mapper.xml 中的 namespace 为 mapper 接口的地址;

mapper 接口 中的方法名和 mapper.xml 中的 定义 的 statement 的 id 保持 一致;

如 果 将 mapper.xml 和 mapper 接 口 的 名 称 保 持 一 致 则 不 用 在 sqlMapConfig.xml 中 进行配置。

(2 )定 义 mapper 接口 :

注意 mapper.xml 的文 件名 和 mapper 的接 口名称保持一致, 且放在同一个目录

(3 )配 置 mapper 扫描 器:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper 接口 包地址

"></property>

<property name="sqlSessionFactoryBeanName" 

value="sqlSessionFactory"/>

</bean>

(4 )使 用扫描器后从 spring 容器 中获取 mapper 的实 现对象。

猜你喜欢

转载自blog.csdn.net/Black_Customer/article/details/107419841