Reputation: 3298
This is one sample document (row) from a collection (table) called product
which is in MongoDB:
{
"_id" : ObjectId("5cb39171528a28f831f"),
"seller" : "Product Seller 1",
"title" : "Product Title 1",
"price" : "159.75",
"brand" : "Product Brand 1",
"productId" : NumberInt(247)
}
The Java Model for this collection looks like this:
@Entity(value = "product", noClassnameStored = true)
@Data
public class Product {
@Id
@Property("_id")
private ObjectId objectId;
private String seller;
private String title;
private String price;
private String brand;
private Long productId;
}
I am using Morphia as a MongoDB Java Driver here. And I am using the Lombok @Data annotation which provides the constructor, getters and setters.
The model works perfectly and is able to fetch data from the DB. My new requirement is to add an additional field in the model. The name of the new field would be stringObjectId
, which will store the value of the objectId
in String format.
Please note that there will not be any changes in the DB document. That is, no new field is getting added to the DB document.
I want that when I am fetching data from the collection in the form of list or a single row
query.asList();
the value in the stringObjectId
should also get populated. Something like this:
stringObjectId = objectId.toString()
No far I have tried to override the setters and the constructor of this model to set the value in the stringObjectId
variable but nothing seems to work. Is there any way this can be achieved?
Upvotes: 0
Views: 110
Reputation: 21285
Check out Morphia LifeCycle events: https://www.playframework.com/modules/morphia-1.2.4/lifecycle-def
The @PostLoad
one will be helpful here. You probably will need @Transient
as well.
Upvotes: 2