MyBatis:collection via annotation in one query

user2022068 picture user2022068 · Nov 29, 2014 · Viewed 10.4k times · Source

I have an xml mapper - one select and one result mapper. It works without problems. But I want to use annotations. My mapper:

  <resultMap id="readItemsRM" type="com.company.Item">
   <id property="id" column="Id"/>
    <result property="comment" column="Comment"/>
    <collection property="textItems" ofType="com.company.TextItem">
        <id property="id" column="TxId"/>
        <result property="name" column="TxName"/>
      </collection>
    </resultMap>

So I did like this

   @Results({
        @Result(id=true, property="id", column="Id"),
        @Result(property="comment", column="Comment"),
        ///,???        
    })
   public List<Item> select();

I can't understand how can I map my collection via annotation without executing one more sql query. As all the examples I found suppose executing one more query. Please help.

Answer

Yigitalp Ertem picture Yigitalp Ertem · Nov 30, 2014

AFAIK, you cannot use JOINs if you are using mapping with annotations.

From the doc, about the usage of @Many,

A mapping to a collection property of a complex type. Attributes: select, which is the fully qualified name of a mapped statement (i.e. mapper method) that can load a collection of instances of the appropriate types, fetchType, which supersedes the global configuration parameter lazyLoadingEnabled for this mapping. NOTE You will notice that join mapping is not supported via the Annotations API. This is due to the limitation in Java Annotations that does not allow for circular references.

You can directly use your ResultMap with annotations if you like:

@Select("SELECT QUERY")
@ResultMap("readItemsRM")
public List<Item> select();