任何人都可以知道哪种是将mjoo中的Pojo对象转换为DBObject的最简单方法。
有一个POJO对象,我需要将其转换为DBObject并返回到不同的实体对象。
实体类:
public class StagingDocument extends AbstractDocument {
@Field("source")
private String source;
@Field("content")
private ContentDocument content;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public ContentDocument getContent() {
return content;
}
public void setContent(ContentDocument content) {
this.content = content;
}
}
public class AbstractDocument extends BaseDocument implements Serializable {
@Field("geoLocation")
private LocationDocument geoLocation = null;
@Field("user")
private UserDocument user = null;
@Field("systemTime")
private long systemTime;
public LocationDocument getGeoLocation() {
return geoLocation;
}
public void setGeoLocation(LocationDocument geoLocation) {
this.geoLocation = geoLocation;
}
public UserDocument getUserInfo() {
return user;
}
public void setUserInfo(UserDocument userInfo) {
user = userInfo;
}
public long getSystemTime() {
return systemTime;
}
public void setSystemTime(long systemTime) {
this.systemTime = systemTime;
}
public class EnrichDocument extends AbstractDocument{
@Field("source")
private String source;
@Field("content")
private ContentDocument content;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public ContentDocument getContent() {
return content;
}
public void setContent(ContentDocument content) {
this.content = content;
}
这里我有StagingDocument,我必须转换为DBObject,然后转换为EnrichDocument。
这就是我试过的
public String saveToEnrichDocument(StagingDocument test) {
Here I need to covert test object to DBObject and then into EnrichDocument entity.
EnrichDocument document = new EnrichDocument();
/* After coverting I have to save it to the db */
EnrichDocument enrichPayload = enrichStagingDocumentRepository.save(document);
String enrichObjectId = enrichPayload.getId().toString();
return enrichObjectId;
}
答案 0 :(得分:1)
在我的一个项目中,我转而使用Morphia作为OR Mapper,它为我做了这些。
一个非常快速的解决方案可能是将POJO序列化为JSON(例如使用GSON),然后使用com.mongodb.util.JSON.parse(..)生成DBObject(反之亦然)。如果你在生产中需要它 - 我不知道我是否会这样做。至少我会用测试来覆盖它。