2017-08-25 96 views
0

在我的日常工作中,我發現將SQL映射到其POJO的必要性。除了POJO本身的列外,我還有一些需要映射到某個地方的計算列。將它映射到POJO中的新變量似乎不是最好的選擇,因爲我實際上不知道需要多少新列(現在和將來)。Mybatis:將部分SQL映射到POJO中的HashMap

實施例:

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

'calculated_column_1' 和 'calculated_column_2' 被,正如其名稱說,計算列取決於另一個表。

我不知道我是否需要1,2或N個計算列。

它如何映射到pojo?

+0

讚賞如果你回答你自己的問題。不是它的問題部分 –

+0

馬上改變它。謝謝 –

回答

1

多次嘗試後,我找到了解決辦法如下:

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

//getters & setters 


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的是這樣的映射後

{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>