构造resultMap以为同一个集合创建不同的实例

时间:2011-05-19 12:02:58

标签: java mybatis

(使用MyBatis v3.0.4。) 我有一个问题,我不知道如何解决。我的对象模型是:

Location.java


public class Location {
    // ... other content
    private List addresses; 
    // ... other content
}

Address.java


public class Address { 
    public enum Type { POSTAL, POBOX, INPUT, CLEANSED } 
    private Type type; 
    private String line1; 
    // ... other content
}

我的SQL是:


SELECT 
    // ... other content 
    postal_address_line_1, 
    postal_address_line_2, 
    postal_address_city, 
    cleansed_address_line_1, 
    cleansed_address_line_2, 
    cleansed_address_city, 
    // ... other content

我如何构建一个插入适当的resultMap 列到正确类型的地址实例并添加到 Location.java中的相同列表?我想避免添加 另一个实例变量到Location.java只是为了保持不同 地址类型。

2 个答案:

答案 0 :(得分:3)

在结果图中使用鉴别器标记。

查看mybatis user guide。搜索“鉴别器”,您会看到更多信息。

<resultMap id="vehicleResult" type="Vehicle">
   <id property=”id” column="id" />
   <result property="sharedPropA" column="shared_column"/>
   <discriminator javaType="int" column="address_type">
     <case value="1" resultMap="postalResultMap"/>
     <case value="2" resultMap="inputResultMap"/>
     <case value="3" resultMap="cleanResultMap"/>
     <case value="4" resultMap="whatIsaCleansedAddressResultMap"/>
   </discriminator>
</resultMap>

加法1:

您需要选择不同行的地址。

select
    postal_address_line_1 as line1, 
    postal_address_line_2 as line2, 
    postal_address_city as city,
    type as 'POSTAL'

...

联合

select
    postal_address_line_1 as line1, 
    postal_address_line_2 as line2, 
    postal_address_city as city,
    type as 'CLEANSED'

.....

然后内置的枚举类型处理程序应该正确设置类型。

答案 1 :(得分:1)

根据Andy Pryor的建议,我能够通过将我的SQL语句更新为以下内容来解决问题:

SELECT 
// ... other content 
'POSTAL' as Postal_Address_Type,
postal_address_line_1, 
postal_address_line_2, 
postal_address_city,
'CLEANSED' as Cleansed_Address_Type,
cleansed_address_line_1, 
cleansed_address_line_2, 
cleansed_address_city, 
// ... other content

然后将我的resultMap更新为以下内容:

<resultMap ...>
    //... other content
    <association property="postalAddress" javaType="com.x.y.z.Address">
        <result property="type" column="Postal_Address_Type"/>
        <result property="line1" column="Address_Part_1_Name"/>
        <result property="line2" column="Address_Part_2_Name"/>
        //...other content
    </association>
    <association property="cleansedAddress" javaType="com.x.y.z.Address">
        <result property="type" column="Cleansed_Address_Type"/>
        <result property="line1" column="Address_Part_1_Name"/>
        <result property="line2" column="Address_Part_2_Name"/>
        //...other content
    </association>
</resultMap>

最后,在我的Address课程中,我能够拥有setType(Type),并且内置的枚举类型处理程序可以实现神奇。在Location类中,我可以只有一个Address实例列表,各种setXXXAddress()方法可以适当地添加到此列表中。

不幸的是,我无法将列插入某种工厂类,但在我看来,将硬编码类型放入SQL语句中并不算太脏。缺点是我引入了域模型的Address.Type值与SQL语句之间的耦合,但鉴于resultMap SQL XML需要在Address中保存实例变量的名称,这种情况已经存在了。无论如何{1}}课程。