[英]Constructing resultMap to create different instances for the same collection
(使用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添加另一个实例变量。
在结果图中使用鉴别标记。
请参阅mybatis用户指南 。 搜索“ discriminator”,您会看到更多信息。
<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'
.....
那么内置的枚举类型处理程序应正确设置类型。
按照安迪·普赖尔(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
类中保存实例变量的名称,这种情况已经存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.