|
Project Information
Members
Featured
Downloads
Wiki pages
Links
|
Morphia is a lightweight type-safe library for mapping Java objects to/from MongoDB:
@Entity("employees")
class Employee {
@Id ObjectId id; // auto-generated, if not set (see ObjectId)
String firstName, lastName; // value types are automatically persisted
Long salary = null; // only non-null values are stored
Address address; // by default fields are @Embedded
Key<Employee> manager; //references can be saved without automatic loading
@Reference List<Employee> underlings = new ArrayList<Employee>(); //refs are stored*, and loaded automatically
@Serialized EncryptedReviews; // stored in one binary field
@Property("started") Date startDate; //fields can be renamed
@Property("left") Date endDate;
@Indexed boolean active = false; //fields can be indexed for better performance
@NotSaved string readButNotStored; //fields can loaded, but not saved
@Transient int notStored; //fields can be ignored (no load/save)
transient boolean stored = true; //not @Transient, will be ignored by Serialization/GWT for example.
//Lifecycle methods -- Pre/PostLoad, Pre/PostPersist...
@PostLoad void postLoad(DBObject dbObj) { ... }
}
...
Datastore ds = ...; // like new Morphia(new Mongo()).createDatastore("hr")
morphia.map(Employee.class);
ds.save(new Employee("Mister", "GOD", null, 0));
Employee boss = ds.find(Employee.class).field("manager").equal(null).get(); // get an employee without a manager
Key<Employee> scottsKey = ds.save(new Employee("Scott", "Hernandez", ds.getKey(boss), 150*1000));
//add Scott as an employee of his manager
UpdateResults<Employee> res = ds.update(boss, ds.createUpdateOperations(Employee.class).add("underlings", scottsKey));
Employee scottsBoss = ds.find(Employee.class).filter("underlings", scottsKey).get(); // get Scott's boss; the same as the one above.
for (Employee e : ds.find(Employee.class, "manager", boss))
print(e);
Please continue by reading the QuickStart or looking at a list of AllAnnotation. Note: @Reference will not save objects, just a reference to them; You must save them yourself. |