如何从Mongo数据源创建不可变的Java对象
我希望直接从Mongo集合创建不可变的Java对象,例如:如何从Mongo数据源创建不可变的Java对象,java,mongodb,Java,Mongodb,我希望直接从Mongo集合创建不可变的Java对象,例如: public final class Sample { private final String description; private final Integer min; private final Integer max; public Sample(String description, Integer min, Integer max) { this.description
public final class Sample {
private final String description;
private final Integer min;
private final Integer max;
public Sample(String description, Integer min, Integer max) {
this.description = description;
this.min = min;
this.max = max;
}
public String getDescription() {
return description;
}
public Integer getMin() {
return min;
}
public Integer getMax() {
return max;
}
}
我一直在使用PojoCodecProvider
保存对象,效果很好。但是,我显然不能用它来加载对象,因为没有arg构造函数:
//Doesn't work
MongoCollection<Sample> samples = db.getCollection("samples", Sample.class);
//不起作用
MongoCollection samples=db.getCollection(“samples”,Sample.class);
有没有一种方法可以做到这一点,而不必从文档中提取所有属性并亲自调用构造函数?将会有很多这样类型的对象,其中一些将相当大,如果有一个方便的方法来做这将是一个很大的帮助
非常感谢。您可以按照mongoDB文档中的说明向类添加BSON注释:
@BsonDiscriminator
公开期末班样本{
私有最终字符串描述;
私有最终整数min;
私有最终整数最大值;
@BsonCreator
公共样本(@BsonProperty(“description”)字符串描述、@BsonProperty(“min”)整数最小、@BsonProperty(“max”)整数最大){
this.description=描述;
this.min=min;
this.max=max;
}
公共字符串getDescription(){
返回说明;
}
公共整数getMin(){
返回最小值;
}
公共整数getMax(){
返回最大值;
}
}
nop,您密封了示例类,因此没有人可以使用默认构造函数,然后,您需要迭代MongoCollection,并在您自己的集合中逐个插入新的样本。真正好的问题是为什么要这样做?@akortex91在服务层中拥有一个不可变的域模型有很多好处:线程安全、缓存、,防止出现NullPointerExceptions
和更多异常。是的,我很清楚这些问题,但是您的具体用例是什么。有时,为实现设计模式付出额外的努力可能不是最好的情况。@akortex91我完全同意,这是我提出这个问题的原因之一。如果不便大于好处,我将重新评估。