为了账号安全,请及时绑定邮箱和手机立即绑定

MyBatis的Mapper支持继承么?或者类似的解决方案?

MyBatis的Mapper支持继承么?或者类似的解决方案?

远看寒山石径斜 2018-03-23 14:04:50
查看完整描述

1 回答

?
Qyou

TA贡献8条经验 获得超4个赞

Mybatis实际上隐藏了一个功能:Mapper.xml可以继承,这个在官方文档中并没有提到过,不过在这个issue (commit)里提到过。

Statement覆盖

利用Mapper.xml的继承机制,我们可以做到ChildMapper覆盖ParentMapper中selectinsertdeleteupdate。下面举例说明:

Interface:

@MybatisMapperpublic interface ParentMapper {  String selectFoo();  String selectBar();
}@MybatisMapperpublic interface ChildMapper extends ParentMapper {  String selectLoo();

}

Mapper.xml:

<mapper namespace="me.chanjar.mybatislearn.inherit.statement.ParentMapper">

  <select id="selectFoo" resultType="String">
    SELECT 'Foo From Parent'
    FROM dual  </select>

  <select id="selectBar" resultType="String">
    SELECT 'Bar From Parent'
    FROM dual  </select></mapper><mapper namespace="me.chanjar.mybatislearn.inherit.statement.ChildMapper">

  <!-- 覆盖 Parent.selectFoo的定义 -->
  <select id="selectFoo" resultType="String">
    SELECT 'Foo From Child'
    FROM dual  </select>

  <!-- 不覆盖 Parent.selectBar的定义 -->

  <!-- 自己的 Child.selectLoo的定义 -->
  <select id="selectLoo" resultType="String">
    SELECT 'Loo From Child'
    FROM dual  </select></mapper>

规律可以总结为:

  1. ParentMapper.xml中有,ChildMapper.xml中没有,ChildMapper沿用ParentMapper.xml中的定义

  2. ParentMapper.xml中有,ChildMapper.xml中也有,ChildMapper使用ChildMapper.xml中的定义

  3. ParentMapper.xml中没有,ChildMapper.xml中有,ChildMapper使用ChildMapper.xml中的定义


查看完整回答
反对 回复 2018-03-23
  • 1 回答
  • 0 关注
  • 2799 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信