Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return list of Object inside Object with MyBatis

I encountered problems when returning a list of Objects inside another Object when using MyBatis. My main object looks like this:

private Long id;

private String symbol;

private List<TypePermission> typePermissions;

and my mapper looks like this

<resultMap type="CalendarType" id="calendarTypeMap">
    <result column="id" property="id"/>
    <result column="symbol" property="symbol"/>
    <collection property="TypePermissions" resultMap="TypePermissions"/>
</resultMap>

<resultMap id="TypePermissions" type="TypePermission">
    <result property="roleId" column="roleId"/>
    <result property="permissionSymbol" column="permissionSymbol"/>
</resultMap>

My goal is to get an object like this:

content:[
    "id":id,
    "symbol":symbol,
    "TypePermissions":{
        "roleId":roleId,
        "permissionSymbol":permissionSymbol
    }
]

When I execute the sql query I get the following an error cannot find symbol TypePermissions, because the main SELECT tries to select rows such as TYPEPERMISSIONS, ID, SYMBOL

I searched over the internet, but failed to find anything useful. Could you help me and point out what am I doing wrong?

like image 958
Yuriy Kravets Avatar asked Jul 04 '15 12:07

Yuriy Kravets


People also ask

What is resultMap in MyBatis?

The resultMap element is the most important and powerful element in MyBatis. It's what allows you to do away with 90% of the code that JDBC requires to retrieve data from ResultSet s, and in some cases allows you to do things that JDBC does not even support.

Can I pass a list as a parameter to a MyBatis Mapper?

NOTE You can pass any Iterable object (for example List, Set, etc.), as well as any Map or Array object to foreach as collection parameter.

Does MyBatis use prepared statement?

The parameter object has a property called sql . That SQL string will be prepared as a JDBC prepared statement in MyBatis. The SQL string also references a property called id . That property - from the same parameter object - will be used as the value of the prepared statement parameter.


1 Answers

Please post your select snippet, I think this will ok:

<select id="selectCalendarType" parameterType="int" resultMap="calendarTypeMap">
    SELECT c.id,
    c.symbol
    t.roleId,
    t.permissionSymbol
    FROM CalendarType c
    LEFT JOIN TypePermission t ON c.id = t.c_id
    WHERE c.id = #{id}
</select>

And I think what you will get is actully something like this:

content:{
  "id":id,
  "symbol":symbol,
  "TypePermissions":[{
    "roleId":roleId,
    "permissionSymbol":permissionSymbol
  }]
}

And more about this you can read this example Nested_Results_for_Collection

like image 174
PhoenixYip Avatar answered Nov 10 '22 00:11

PhoenixYip