多くのインスタンス フィールドを持つ (Java) クラスがあります (その多くはオプションです)。すべてのフィールド (したがってクラス) を不変にしたいと考えています。そのため、クラスのインスタンスを構築するために Builder パターンを使用したいと思います。
Builder パターンを使用してクラスのインスタンスを作成するように myBatis を構成できますか? myBatis にマップを返させ、そのマップを使用してコード内のインスタンスをビルドできることはわかっています。ただし、Java Beans とコンストラクターを使用してインスタンスを作成する方法と同様に、このマッピングを構成する (または何らかの規則を使用する) 方法を探しています。
編集(例を含めるため)
次に例を示します。
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) を呼び出させるにはどうすればよいですか?