Search code examples
mybatisspring-mybatis

How to make mybatis to map a list to Object


I have a device table which defines the device entity:

device:
   id:
   type:

And I have a attribute table which records the device's attributes:

device_attr:
   device_id:
   key:
   value:

How can I write the mappers to save the device POJO into the table and how to load the attributes into the POJO? thanks.

Pivot function may meet this, but, mysql doesnt support it, and it's performance is not good.


Solution

  • In order to save the object you can use dynamic sql to iterate over POJO properties and generate INSERT statements similar to what is described in How to use MyBatis to iterate all fields of an object? :

    <bind name="deviceProperties"
      value="@org.apache.commons.beanutils.BeanUtils@describe(myDevice).entrySet()" />
    
    <foreach index="propertyName" item="propertyValue" collection="deviceProperties">
       INSERT INTO device_attr (key, value) values (
            ${propertyName}, ${propertyValue});
    </foreach>
    

    There is no out of the box solution to do the same for the select.

    You need to do what is called table pivot but this is very database specific.

    Another option is to recreate the POJO from the list of fields in java. It can be done in mapper using default methods like described in this answer.