Reputation: 6271
Can anyone know which is the easiest way to convert the Pojo object to DBObject in mongo.
Have a POJO object which I need to convert to DBObject and back to different entity object.
Entity class:
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;
}
Here I have StagingDocument which I have to convert to DBObject and then into EnrichDocument.
This is what I tried
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;
}
Upvotes: 2
Views: 3369
Reputation: 186
In one of my projects I switched to Morphia as an OR Mapper which does this stuff for me.
A very quick solution could be to serialize the POJO to JSON (for example with GSON) and then use com.mongodb.util.JSON.parse(..) to generate the DBObject (and vice versa the same way). If you need it in production - I don't know if I'd go that way. At least I'd cover it with Tests.
Upvotes: 1