Mybatis: 将 SQL 的一部分映射到 POJO 内部的 HashMap

Mybatis: Map part of the SQL to HashMap inside POJO

在日常工作中,我发现有必要将一个SQL映射到它的POJO上。除了 POJO 本身的列之外,我还有一些需要映射到某处的计算列。将它映射到 POJO 中的新变量似乎不是最佳选择,因为我实际上不知道我需要多少新列(现在和将来)。

示例SQL:

select id, name, surname, 
  calculated_column_1, calculated_column_2, ... 
  from person
  left outer join ...

calculated_column_1calculated_column_2 是——正如它们的名字所说的——根据另一个 table.

计算的列

我不知道我是否需要 1、2 或 N 个计算列。

如何映射到pojo?

经过多次尝试,我找到了如下解决方案:

POJO:

private int id;
private String name;
private String surname;
private HashMap<String, Object> aditionalColumns;

// getters & setters

MyBatis 映射器:

<resultMap id="BaseResultMap" type="Person" automapping="true">
  <id column="id" property="id"/>
  <association
      property="aditionalColumns"
      resultMap="aditionalColumnsMapper" 
      columnPrefix="calculated_" />
</resultMap>

<resultMap id="aditionalColumnsMapper" type="map" autoMapping="true"/>

在这种情况下,映射后我的 aditionalColumns HashMap 将如下所示:

{column_1=value1, column_2=value2}

注意:我不知道我需要多少列,如果你确切地知道你需要多少,并且它不会改变,你可以只映射你的列改变第二个 resultMap 如下:

<resultMap id="aditionalColumnsMapper" type="map">
    <result column="calculated_column_1" property="calculated_column_1"/>
    <result column="calculated_column_2" property="calculated_column_2"/>
</resultMap>