2012-03-24 48 views
2

我有一個選擇在mapper.xml文件中定義:MyBatis的@Select引用選擇在XML映射文件中定義

<mapper namespace="foo"> 

    <select id="selectWithRoles" parameterType="String" resultMap="personWithRoles"> 
    select * 
    from 
    PERSON P 
    left outer join PERSON_ROLE R on P.ID = R.PERSON_ID 
    where P.ID = #{id} 
    </select> 

    <resultMap id="personWithRoles" type="Person"> 
    <id property="id" column="ID" /> 
    <collection property="roles" ofType="Role"> 
     <id property="personId" column="PERSON_ID"/> 
     <result property="name" column="NAME"/> 
    </collection> 
    </resultMap> 

</mapper> 

,我想通過註解(S)不復制的SELECT語句通過DAO接口公開這個選擇進入DAO。以下工作正常:

@Select("select * from PERSON P left outer join PERSON_ROLE R on P.ID = R.PERSON_ID where P.ID = #{id}") 
@ResultMap("personWithRoles") 
public Person loadByIdWithRoles(String id); 

但我不喜歡複製SQL到註釋(可能是相當長的)希望是這樣的:

@Select("selectWithRoles") 
public Person loadByIdWithRoles(String id); 

其中「selectWithRoles」是選擇ID在XML定義。可能嗎?

回答

2

找到了答案。如果有人需要它:顯然,只要XML文件中的名稱空間與接口的完全限定名稱相匹配,並且方法名稱與XML中的id相匹配,那麼MyBatis就會奇蹟般地使它無需註釋。

<mapper namespace="foo"> 

    <select id="selectWithRoles" parameterType="String" resultMap="personWithRoles"> 
    select * 
    from 
    PERSON P 
    left outer join PERSON_ROLE R on P.ID = R.PERSON_ID 
    where P.ID = #{id} 
    </select> 

    <resultMap id="personWithRoles" type="Person"> 
    <id property="id" column="ID" /> 
    <collection property="roles" ofType="Role"> 
     <id property="personId" column="PERSON_ID"/> 
     <result property="name" column="NAME"/> 
    </collection> 
    </resultMap> 

</mapper> 

注意,包名與XML和方法名的命名空間相匹配匹配選擇ID:

package foo; 
public Person public Person selectWithRoles(String id); 
+0

這正是我一直在尋找。非常感謝! – codematix 2017-09-06 19:06:55