I resolved this by putting my elements into a DTO.
Rest Service that returns table rows with Embedded element from MongoDB using Morphia
Question
I am creating a rest service that hits a MongoDB, and returns the results of a query. However, I am having some confusion about how to return the embedded elements of the query.
My Teacher Entity looks like so:
package org.dummy.entities;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;
@Entity("teachers")
public class Teacher {
@Id
private ObjectId id;
@Property("first_name")
private String first;
@Property("middle_initial")
private String middle;
@Property("last_name")
private String last;
@Property("url")
private String url;
@Embedded("info")
private TeacherInfo info;
}
My TeacherInfo Entity looks like so:
package org.dummy.entities;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Property;
@Embedded
public class TeacherInfo {
@Property("address")
private String address;
@Property("phone")
private String phone;
@Property("grade")
private String grade;
}
And my Service to get all teachers looks like this:
package org.dummy.services;
import java.util.List;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.dummy.entities.Teachers;
import org.dummy.entities.TeacherInfo;
@Path("/teachers")
public class TeacherService {
private Datastore db;
public static final String DB_NAME = "test_db";
@Path("/all/")
@GET
@Produces("application/json")
public List<Teacher> getAllTeachers() {
Datastore ds = getDatastore();
return ds.createQuery(Teacher.class).asList();
}
private Datastore getDatastore() {
try {
Mongo mongo = new Mongo("localhost", 27017);
db = new Morphia().map(Teacher.class).map(TeacherInfo.class).createDatastore(mongo, DB_NAME);
}
catch (Exception e) {
throw new RuntimeException("Error initializing mongo db", e);
}
return db;
}
}
On Mongo command line, if I run db.teachers.find(), I get:
{
"_id": ObjectId("5367f8b326d508614e3c4aa4"),
"info": {
"address": "dummy address",
"phone": "(555) 867-9305",
"grade": "K"
},
"first_name": "Jane",
"middle_initial": "P",
"last_name": "Doe",
"url": "<host>/teachers/Jane_P_Doe/"
}
However if I run the service I get:
[{
"_id": ObjectId("5367f8b326d508614e3c4aa4"),
"first_name": "Jane",
"middle_initial": "P",
"last_name": "Doe",
"url": "<host>/teachers/Jane_P_Doe/"
}]
I would like to get out the info as well, how do I go about doing this?
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow