【发布时间】:2013-03-28 16:08:22
【问题描述】:
我有一个 (Java) 类,其中包含许多实例字段(其中许多是可选的)。我希望所有字段(因此类)都是不可变的。所以,我想使用 Builder Pattern 来构造类的实例。
我可以配置 myBatis 以使用 Builder 模式创建一个类的实例吗?我知道我可以让 myBatis 返回一个地图并使用该地图在我的代码中构建实例。但是,我正在寻找一种配置此映射(或使用某种约定)的方法,类似于如何通过使用 Java Bean 和构造函数来创建实例。
编辑(包括示例)
这是一个例子:
package com.example.model;
// domain model class with builder
public final class CarFacts {
private final double price;
private final double numDoors;
private final String make;
private final String model;
private final String previousOwner;
private final String description;
public static class Builder {
// required params
private final double price;
private final String make;
private final String model;
// optional params
private final String previousOwner;
private final String description;
private final double numDoors;
public Builder(double price, String make, String model) {
this.price = price;
this.make = make;
this.model = model;
}
public Builder previousOwner(String previousOwner) {
this.previousOwner = previousOwner;
return this;
}
// other methods for optional param
public CarFacts build() {
return new CarFacts(this);
}
}
private CarFacts(Builder builder) {
this.price = builder.price;
//etc.
}
}
然后,我有一个映射器:
<!-- this doesn't work but I think h3adache suggest that I could have the resultType
be com.example.model.CarFacts.Builder and use the Builder constructor. But I'm not sure how
I would call the methods (such previousOwner(String)) to populate optional params -->
<mapper namespace="com.example.persistence.CarFactsMapper">
<select id="selectCarFacts" resultType="com.example.model.CarFacts">
select *
from CarFacts
</select>
</mapper>
最后,我有了映射器界面:
package com.example.persistence.CarFactsMapper;
public interface CarFactsMapper {
List<CarFacts> selectCarFacts();
}
我还希望能够通过 myBatis 使用静态工厂方法创建实例。例如:
public final class Person {
private final String lastName;
private final String firstName;
private Person(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public Person newInstance(String lastName, String firstName) {
return new Person(lastName, firstName);
}
}
具体来说,如何让 myBatis 调用 newInstance(String, String)?
【问题讨论】:
-
根据我的经验,您无法将最终/不可变字段映射到您的 pojos/beans 中。还可以查看mybatis.org/mybatis-3/sqlmap-xml.html#Result_Maps 进一步阅读构造函数注入。
标签: java mybatis builder-pattern static-factory