Mybatis Mapper.xml繼承機制

Mapper.xml繼承機制

github地址java

Mybatis實際上隱藏了一個功能:Mapper.xml能夠繼承,這個在官方文檔中並無提到過,不過在這個issue (commit)裏提到過。git

Statement覆蓋

利用Mapper.xml的繼承機制,咱們能夠作到ChildMapper覆蓋ParentMapper中selectinsertdeleteupdate。下面舉例說明:github

Interface:sql

@MybatisMapper
public interface ParentMapper {

  String selectFoo();

  String selectBar();
}

@MybatisMapper
public interface ChildMapper extends ParentMapper {

  String selectLoo();

}

Mapper.xml:mybatis

<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>

規律能夠總結爲:app

  1. ParentMapper.xml中有,ChildMapper.xml中沒有,ChildMapper沿用ParentMapper.xml中的定義
  2. ParentMapper.xml中有,ChildMapper.xml中也有,ChildMapper使用ChildMapper.xml中的定義
  3. ParentMapper.xml中沒有,ChildMapper.xml中有,ChildMapper使用ChildMapper.xml中的定義

相關代碼:Java代碼測試代碼配置文件測試

ResultMap覆蓋

Mapper.xml繼承機制只針對statement有效,對於sqlresultMap是無效的。
若是要在ChildMapper.xml中覆蓋這些,必需要先覆蓋ParentMapper.xml中的statement,而後讓這些statement使用新的sqlresultMap等。spa

下面舉例一個給ITEM表添加字段,可是不修改原來的ItemMapper的例子:code

Model:xml

public class Item {

  private Integer id;
  private String title;
  // setter and getter ...
}

public class ItemEx extends Item {

  private String name;
  // setter and getter ...

}

Interface:

@MybatisMapper
public interface ItemMapper {

  Item getById(@Param("id") Long id);

}
@MybatisMapper
public interface ItemExMapper extends ItemMapper {

}

Mapper.xml:

<mapper namespace="me.chanjar.mybatislearn.inherit.resultmap.ItemMapper">

  <select id="getById" resultMap="Item">
    select
      *
    from item where id = #{id}
  </select>

  <resultMap id="Item" type="me.chanjar.mybatislearn.inherit.resultmap.Item" autoMapping="true">
    <id property="id" column="id" />
  </resultMap>

</mapper>

<mapper namespace="me.chanjar.mybatislearn.inherit.resultmap.ItemExMapper">

  <!-- 若是這裏不寫一遍,就會用到ItemMapper.getById的定義,resultMap就不會是ItemEx-->
  <select id="getById" resultMap="Item">
    select
    *
    from item where id = #{id}
  </select>

  <resultMap id="Item" type="me.chanjar.mybatislearn.inherit.resultmap.ItemEx" autoMapping="true">
    <id property="id" column="id" />
  </resultMap>

</mapper>

相關代碼:Java代碼測試代碼配置文件

相關文章
相關標籤/搜索