2012-03-24 5 views
2

マッパーXMLファイルで定義された選択参照:MyBatisの@Selectは、私がmapper.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> 

と私は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をコピーする好きではない:以下は、正常に動作します「selectWithRolesは」選択のID XMLで定義されているが、

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

です。出来ますか?

答えて

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

関連する問題