Query By Example

136 views
Skip to first unread message

gutzeit

unread,
Feb 6, 2011, 4:32:02 PM2/6/11
to mor...@googlegroups.com
Hi,

Is there a way to execute query by example using Morphia?

Something like:

User exampleUser = new User("em...@ddd.com");
User realUser = ds.createQuery(User.class).filter("this", exampleEntity).get();

Scott Hernandez

unread,
Feb 6, 2011, 5:20:15 PM2/6/11
to mor...@googlegroups.com
No, but I can add it to the list. You can do this with embedded
objects, just not the root entity.

I'm thinking something like:

ds.QBE(exampleUser).get/asList()

Is QBE a good method name, or maybe "queryByExample"?

gutzeit

unread,
Feb 6, 2011, 6:01:25 PM2/6/11
to mor...@googlegroups.com
queryByExample sounds pretty straight forward :-)

BTW, I can do it now like this:

User example = new User();
example.setEmail("em...@gmail.com");
DBObject dbObject = morphia.toDBObject(example);
BasicDBObject userEntryDbObj = (BasicDBObject) ds.getDB().getCollection("users").findOne(dbObject);
User userEntry = morphia.fromDBObject(User.class, userEntryDbObj);

But its does not look "morpheesh" :-)

Scott Hernandez

unread,
Feb 6, 2011, 6:05:00 PM2/6/11
to mor...@googlegroups.com
Yeah, I didn't give that example, but that is one of the current
work-arounds. I added the feature. It will be 1.0.

gutzeit

unread,
Feb 6, 2011, 6:23:23 PM2/6/11
to mor...@googlegroups.com
Scott, when is 1.0 planned to be released ?


BTW, If anyone is interested in a workaround meanwhile, a generic method of doing so:


public D getByExample(D example, Class objectClass) {
    DBObject dbObject = morphia.toDBObject(example);
    // Find out the entity name by reflection.
    Entity annotation = (Entity) objectClass.getAnnotation(Entity.class);
    String collectionName = annotation.value();

    BasicDBObject entryDbObj = (BasicDBObject) ds.getDB().getCollection(collectionName).findOne(dbObject);
    D entry = (D) morphia.fromDBObject(objectClass, entryDbObj);
    return entry;
}

Scott Hernandez

unread,
Feb 6, 2011, 6:44:01 PM2/6/11
to mor...@googlegroups.com
On Sun, Feb 6, 2011 at 3:23 PM, gutzeit <gut...@gmail.com> wrote:
> Scott, when is 1.0 planned to be released ?

When the code is done :)

I will put up a snapshot today.

This is not the best code because it assumes that you specify the
collection name in the @Entity annotation; It is also very low-level.

You can use the Query(Impl) class to do most of this stuff which makes
it much cleaner.
http://code.google.com/p/morphia/source/browse/trunk/morphia/src/main/java/com/google/code/morphia/DatastoreImpl.java

gutzeit

unread,
Feb 7, 2011, 1:44:07 AM2/7/11
to mor...@googlegroups.com
Yeap, thanks. My knowledge of Query is very limited, I will try to do better.
Waiting for snapshots ;-)


Scott Hernandez

unread,
Feb 7, 2011, 9:24:45 AM2/7/11
to mor...@googlegroups.com
The snapshot is up.
Reply all
Reply to author
Forward
0 new messages