001 package com.khubla.pragmatach.plugin.mongodb; 002 003 import com.khubla.pragmatach.framework.api.PragmatachException; 004 import com.khubla.pragmatach.plugin.mongodb.db.DBCollectionFactory; 005 import com.khubla.pragmatach.plugin.mongodb.serializer.BasicObjectSerializer; 006 import com.khubla.pragmatach.plugin.mongodb.serializer.ObjectSerializer; 007 import com.mongodb.BasicDBObject; 008 import com.mongodb.DBCollection; 009 import com.mongodb.DBCursor; 010 import com.mongodb.DBObject; 011 012 /** 013 * @author tom 014 */ 015 public class MongoDBObjectPersister { 016 /** 017 * DBCollection 018 */ 019 private final DBCollection dbCollection; 020 /** 021 * serializer 022 */ 023 private final ObjectSerializer objectSerializer; 024 025 public MongoDBObjectPersister(Class<?> typeClazz) { 026 objectSerializer = new BasicObjectSerializer(typeClazz); 027 dbCollection = DBCollectionFactory.getInstance().getDBCollection(typeClazz); 028 } 029 030 /** 031 * find an instance by an id 032 * 033 * @return 034 */ 035 public DBObject find(String id) throws PragmatachException { 036 final BasicDBObject basicDBObject = new BasicDBObject(); 037 basicDBObject.append(MongoDBDAO.ID, id); 038 final DBCursor dbCursor = dbCollection.find(basicDBObject); 039 if (dbCursor.hasNext()) { 040 return dbCursor.next(); 041 } else { 042 return null; 043 } 044 } 045 046 public Object load(DBObject dbObject) throws PragmatachException { 047 try { 048 return objectSerializer.deserialize(dbObject); 049 } catch (final Exception e) { 050 throw new PragmatachException("Exception in load", e); 051 } 052 } 053 054 public void save(Object object) throws PragmatachException { 055 try { 056 /* 057 * save 058 */ 059 final BasicDBObject basicDBOBject = objectSerializer.serialize(object); 060 dbCollection.save(basicDBOBject); 061 } catch (final Exception e) { 062 throw new PragmatachException("Exception in save", e); 063 } 064 } 065 }