Reputation: 58
How to load two attributes of reference document/entity using morphia
I have a Class Person and School like this
person class
@Entity
public class Person {
@Id private ObjectId id;
private String name;
@Embedded private PersonEducation schoolInfo;
}
@Embedded
public class PersonEduction {
@Reference private School school;
private String year;
private String degree;
}
School Class
@Entity
public class School {
@Id private ObjectId id;
private String name;
private String address;
private String description;
}
How I can get id and and name fields of School in Person class example When i want to person
Person person = datastore.find(Person.class).field("name").equals("xyz").get();
person.gerSchoolInfo();
Response (Not want all School class fields)
{school:{_id:ObjectId("4fcef3e20364a375e7631fb0"), name:"SchoolA"}, year:"1990", degree:"MBA" }
and If I query school where _id=ObjectId("4fcef3e20364a375e7631fb0"), I get all School fields
{_id:ObjectId("4fcef3e20364a375e7631fb0"), name:"xyz", address="some add", description="some desc"}
Upvotes: 1
Views: 2227
Reputation: 4493
Instead of using @Reference
you should use
key<School> school;
and use custom query to load it.
datastore.createQuery(School.class).retrivedFields(true, "id","name");
Upvotes: 1
Reputation: 9685
To give an alternative to mtariq, replace
@Reference private School school;
with
private ObjectId schoolId;
and fetch it yourself. However since your School class is so simple I think you'd be better off using Lazy loading, so:
@Reference @Lazy private School school;
This will only load the school object when/if it is referenced.
Upvotes: 0