Search code examples
javamybatisibatis

How to map multiple beans in Mybatis?


I have two beans (1) CarBean and (2) WheelBean as follow

public class CarBean implements Serializable {
  private Long carId;
  private List<WheelBean> wheels;
}

I have two tables for car and wheel. I would like to query data from car table and use left-join to wheel table. I would like to use as follow

  <select id='getCarById' parameterType='Long' resultType='mypackage.CarBean'>
    SELECT
     C.*,W.*
     FROM CAR C
     LEFT JOIN WHEEL W
     ON C.CAR_ID = W.CAR_ID
     WHERE CAR_ID = #{carId}
  </select>

But this way , I can't get datas from wheel table because there has no matching datas for wheel information. So , now I am using as extends CarBean to WheelBean and at my datasource xml is

  <select id='getCarById' parameterType='Long' resultType='mypackage.WheelBean'>
    SELECT
     C.*,W.*
     FROM CAR C
     LEFT JOIN WHEEL W
     ON C.CAR_ID = W.CAR_ID
     WHERE CAR_ID = #{carId}
  </select>

This way , I can get both CarBean and WheelBean datas. My problem is that ".. has there any way to get both carBean and wheelBean datas without extending carBean to wheelBean ?"

I think in normal , WheelBean should extends CarBean rather than CarBean from. Am I right ? At my service layer , WheelBean List is composite in CarBean. How would I do ?


Solution

  • You can map as many as you want but MyBatis will provide query result through a method queryForObject or queryForList or some other...

    No method in the world can return two value.
    so only way is to bind them in one class.

    Now as you don't want extending carBean to wheelBean so you can give it a try

    • Create another class for result containing purpose which will contains both carBean and wheelBean as property

    • then make result map like

      <resultMap class="mypackage.YourNewClass" id="mapId">
      <result property="carBean.pro1" column="" />
      <result property="carBean.pro2" column="" />
      ......
      <result property="wheelBean.pro1" column="" />
      <result property="wheelBean.pro2" column="" />

    • then show this result map to select query

      <select id="getCarById" resultMap="mapId" parameterClass="Long">