I have a (Java) class with many instance fields (many of which are optional). I would like all fields (thus class) to be immutable. So, I would like to use the Builder Pattern for constructing instances of the class.
Can I configure myBatis to create an instance of a class using the Builder Pattern? I know that I could have myBatis return a map and use that map to build in the instance in my code. However, I'm looking for a way to configure this mapping (or use some convention) similar to how can create instance via use of Java Beans and constructors.
Edit (to include an example)
Here's an example:
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.
}
}
Then, I have a mapper as:
<!-- 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>
Finally, I have the mapper interface:
package com.example.persistence.CarFactsMapper;
public interface CarFactsMapper {
List<CarFacts> selectCarFacts();
}
I would also like to be able to create instances using a static factory method via myBatis. For example:
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);
}
}
Specifically, how can I have myBatis call newInstance(String, String)?