Mybatis:将SQL的一部分映射到POJO中的HashMap [英] Mybatis: Map part of the SQL to HashMap inside POJO

查看:299
本文介绍了Mybatis:将SQL的一部分映射到POJO中的HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my daily work, I found the necessity of mapping a SQL to its POJO. Besides the columns of the POJO itself, I had some calculated columns that needed to map somewhere. Mapping it to new variables in the POJO didn't seem the best option, as I actually didn't know how many new columns I would need (now and in the future).

示例SQL:

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

calculated_column_1calculated_column_2是-顾名思义-取决于另一个表的计算列.

calculated_column_1 and calculated_column_2 are -- as their name say -- calculated columns depending of another table.

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

I didn't know if I was going to need 1, 2 or N calculated columns.

如何将其映射到pojo?

How can it be mapped to the pojo?

推荐答案

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

After many tries, I found the solution as follows:

POJO:

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

// getters & setters

MyBatis映射器:

MyBatis Mapper:

<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如下所示:

In this case, my aditionalColumns HashMap would look like this after mapping:

{column_1=value1, column_2=value2}

注意:我不知道我需要多少列,如果您确切知道需要多少列,并且它不会更改,则只能映射您的列,更改第二个resultMap,如下所示:

Note: I didn't know how many columns I needed, if you know exactly how many you need, and it won't change, you can map only your columns changing the second resultMap as follows:

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

这篇关于Mybatis:将SQL的一部分映射到POJO中的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆