简体   繁体   中英

Creating a separate object for each row of results-set in MyBatis

I am using MyBatis to query DB. I am trying to separate out the results into different objects, but MyBatis is combining the results. I mean, when I try to map the results as explained below, I get a list of 2 Make objects with Toyota having 3 Model objects in the models List and Honda having 2 Model objects in the models list.

Instead I want to get a list of 5 objects and each of them having 1 Model object in the models List.

Could anyone help me out here?

I have 2 POJOs as below

class Make {
    long makeId;
    String makeName;
    List<Model> models;

    // Getter and setters
}

class Model {
    long modelId;
    String modelName;
}

I have a query that extracts the results in the below format.

在此处输入图片说明

My Resultset looks like

<resultMap type='Make' id='resultMap'>
    <id property='makeId' column='make_id' />
    <result property='makeName' column='make_name' />
    <collection property="models" ofType="Model" javaType="list">
        <id property='modelId' column='model_id' />
        <result property='modelName' column='model_name' />
    </collection>
</resultMap>

If I understand correctly, you basically want to identify the parent object Make by the composite key of make_id and model_id .

The following result map may return the result you expect.

<resultMap type='Make' id='resultMap'>
  <id property='makeId' column='make_id' />
  <id column="model_id" /><!-- added -->
  <result property='makeName' column='make_name' />
  <collection property="models" ofType="Model" javaType="list">
    <id property='modelId' column='model_id' />
    <result property='modelName' column='model_name' />
  </collection>
</resultMap>

By omitting property attribute from the <id /> , the column model_id is not mapped to Make , but is used to identify it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM