maximdim
maximdim

Reputation: 8169

MyBatis @Select referencing select defined in mapper XML file

I have a select defined in mapper.xml file:

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

and I want to expose this select via DAO Interface through annotation(s) without copying select statements into DAO. Following works fine:

@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);

But I don't like copying SQL into annotation (could be pretty long) want something like this:

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

where "selectWithRoles" is id of select defined in XML. Is it possible?

Upvotes: 2

Views: 4573

Answers (1)

maximdim
maximdim

Reputation: 8169

Found an answer. In case anybody would need it: apparently as long as the namespace in the XML file matches the fully qualifies name of interface AND the method name matches the id in XML, then MyBatis will magically make it work with no annotation.

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

Note that package name matches with namespace in XML and method name matches select id:

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

Upvotes: 3

Related Questions