Skip to content

JAX RS support for MongoDB

angelozerr edited this page Dec 18, 2012 · 3 revisions

JAX-RS support for MongoDB

Provides several MesageBodyReader/MesageBodyWriter. See https://github.com/angelozerr/mongo-jee/tree/master/src/main/java/com/mongodb/jee/jaxrs

Once you have registered those JAX-RS Provider in your Web Application, you can use DBObject, DBCursor and PageResult in your service.

Use DBObject

@GET
@Path("/findOne")
@Produces(MediaType.APPLICATION_JSON)
public DBObject findOne() {
	DB db = MongoProvider.getMongo().getDB("contact");
	DBCollection col = db.getCollection("persons");
	return col.findOne();
}

Use DBCursor

@GET
@Path("/find")
@Produces(MediaType.APPLICATION_JSON)
public Iterable<DBObject> find() {
	DB db = MongoProvider.getMongo().getDB("contact");
	DBCollection col = db.getCollection("persons");
	return col.find();
}

Use PageResult

@GET
@Path("/findPage")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PageResult findPage(int fromItemIndex, int toItemIndex) {
	DB db = MongoProvider.getMongo().getDB("contact");
	DBCollection col = db.getCollection("persons");
	return new PageResult(col.find(), fromItemIndex, toItemIndex);
}

Use PageResult and PageRangeRequest

@GET
@Path("/findPageRange")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public PageResult findPage(PageRangeRequest range) {
	DB db = MongoProvider.getMongo().getDB("contact");
	DBCollection col = db.getCollection("persons");
	return new PageResult(col.find(), range.getFromIndex(),
			range.getToIndex());
}

Clone this wiki locally