![](/img/trans.png)
[英]MyBatis dynamic ResultMap. How to return list of different POJO objects?
[英]MyBatis resultMap with a Builder in the POJO
假設我有一個Java類,代表使用構建器模式的Person:
package com.xyz.domain;
public class Person {
private final int id;
private final String firstName;
private final String middleName;
private final String lastName;
private final String address;
private final String country;
private Person(PersonBuilder builder) {
this.id = id;
this.firstName = builder.firstName;
this.middleName = builder.middleName;
this.lastName = builder.lastName;
this.address = builder.address;
this.country = builder.country;
}
// getters go here
public static class PersonBuilder {
private int id;
private final String firstName;
private final String lastName;
private String middleName;
private String address;
private String country;
public PersonBuilder(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public PersonBuilder withMiddleName(String middleName) {
this.middleName = middleName;
return this;
}
public PersonBuilder withAddress(String address) {
this.address = address;
return this;
}
public PersonBuilder withCountry(String country) {
this.country = country;
return this;
}
public Person build() {
return new Person(this);
}
}
}
我想以此作為mybatis resultMap
的type
,如下所示:
<resultMap id="Person" type="com.xyz.domain.Person">
<id property="id" column="id" />
<result property="firstName" column="first_name" />
<result property="middleName" column="middle_name" />
<result property="lastName" column="last_name" />
<result property="address" column="address" />
<result property="country" column="country" />
</resultMap>
但是,當我調用使用此結果映射的端點時,這會在Spring應用程序中產生500錯誤。 我也嘗試過將resultMap
的type
參數設置為com.xyz.domain.Person.PersonBuilder
並得到一個錯誤。 有什么辦法可以在不犧牲Person類中的構建器模式的情況下進行此工作?
用@Alias(“ Person”)批注標記POJO。 還要確保在配置myBatis數據連接時,包含了com.xyz.domain軟件包來掃描POJO。
我可以通過更新結果圖來解決此問題
<resultMap id="Person" type="com.xyz.domain.Person$PersonBuilder">
<constructor>
<idArg name="id" column="id" />
<arg name="firstName" column="first_name" />
<arg name="lastName" column="last_name" />
</constructor>
<result property="middleName" column="middle_name" />
<result property="address" column="address" />
<result property="country" column="country" />
</resultMap>
這將創建一個PersonBuilder對象列表,但是很容易遍歷該列表並在java中的每個列表項上調用build()
方法: personBuilderList.stream().map(Person.PersonBuilder::build).collect(toList())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.