Search code examples
morphiatype-safety

Benefits of type-safe library (Morphia)


I'm thinking to use Morphia with my GWT mongoDB project but I'm wondering what are the benefits of type-safe library like Morphia? Thanks


Solution

  • It's type-safe. No, kidding aside, the Morphia API is much nicer to interact with.

    To save an entity with the plain Java driver you'd do something like this:

    DBCollection table = db.getCollection("user");
    BasicDBObject document = new BasicDBObject();
    document.put("name", "xeraa");
    document.put("age", 30);
    document.put("createdDate", new Date());
    table.insert(document);
    

    So you are basically putting together plain DBObjects - for inserting, updating, and querying like this:

    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("age", "30");
    DBCursor cursor = table.find(searchQuery);
    

    In Morphia you annotate your entities in a JPA like fashion:

    @Entity
    class FooEntity {
        private String name;
        private Integer age;
        private Date date = new Date();
    }
    

    So you create your objects and simply persist them. Also the fluent query interface is much nicer where you can do things like ds.createQuery(FooEntity.class).field("age").equal(30).asList();