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

标签 java mybatis

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

位置.java


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

地址.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 user guide .搜索“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'

.....

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

关于java - 构造resultMap为同一个集合创建不同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6058319/

相关文章:

java - 为什么每个实体都应该有单独的 MyBatis 映射器?

java - Mybatis 逆关系导致对象重复

java - 如何使用ApplicationListener ConfigurableApplicationContext启动的服务

MyBatis - 根据 javaType 的 ResultMap

java - 当我尝试使用 getter 访问我为父类(super class)创建作为实例变量的列表时,为什么我不断收到错误?

java - Spring Boot-2.1.3 : Parallel Methods Invocation with @Async with CompletableFuture

java - java mail api 邮件发送成功与否

java - 可外部化还是可序列化?

java - 使用 JPA 在浏览器存储中持久保存第 3 方实体

java - MyBatis - 将存储过程输出参数值映射到 POJO