SyntaxHighlighter

Monday, July 4, 2011

Spring - MongoDB (Document Oriented Database)

We often hear following terms viz high scalability, elasticity , high availability..
In addition to this, we do face performance issues with humongous data , which brings our critical applications to deadly halt.

I have experienced such performance problems numerous times in my professional carrier (almost 6 years til now), we usually solved these problems with trade offs like minimizing data fetched / even gone ahead and moved on to more cores and disks etc or tuning and other stuff.

Having such a experience , I was always looking to try out thing called NOSQL databases, recently I got chance & time

My first reaction to Mongo was ..."Its Kool !!".

I tried MongoDB along with spring , (spring-data mongodb), as always spring provides nice abstraction and spring style templates to interact with mongo.

 Setting up MongoDB is very simple,
1. Download zip from http://www.mongodb.org/downloads appropriate for your platform.For me its mongodb-win32-i386-1.8.1.zip
2. Unzip the zip the downloaded zip to a directory, it will have a bin directory with mongo executables.
3. To get mongo working create "C:\data\db\"  ,as mongo uses this location as default to store file system.
4. You are almost done, now go to bin directory and run mongod.exe , this will start up database server.
5. "help' command will help you after that, to explore more functions like creating database, switching, adding users, adding updating/ removing collections.

Now, will move to spring -mongo part,

Spring comes with MongoTemplate, 
sample configurations , that I tried are as follows



The class MongoRepository is a implementation of below interface with mongotemplate instance injected in it



Constructor of MongoRepository initializes a mongoTemplate instance as follows



 It works very smoothly..

 @Override
    public void saveEntity(String collectionName, Entity object,com.dhananjay.ithinker.persister.Repository.Mode mode) {
        log.info("Saving record for in Collection Name "+collectionName);
        switch(mode){
            case INSERT:
                this.mongoTemplate.insert(collectionName,object);
                break;
            case UPDATE:
            { 
                Map objectMap;
                try {
                    objectMap = org.apache.commons.beanutils.BeanUtils.describe(object);
                    Update update = new Update();
                    if(objectMap != null && !objectMap.isEmpty()){
                      
                        for(Map.Entry entry : objectMap.entrySet()){
                            if(entry.getValue() != null)
                                //update.addToSet(entry.getKey(), entry.getValue());
                                update = update.set(entry.getKey(), entry.getValue());
                            this.mongoTemplate.updateFirst(collectionName,new Query(where("_id").is(object.getId())), update);
                        }
                    }
                  
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Error while update ",e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException("Error while update ",e);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Error while update ",e);
                }
                break;
            }
            case DELETE:
                this.mongoTemplate.remove(collectionName,new Query(where("_id").is(object.getId())));
                break;
            default :
                throw new UnsupportedOperationException("This mode for DB operation is not yet supported "+mode);
      
        }
      
        log.info("Saving record for in Collection Name is completed"+collectionName);
    }


@Override
    public T getEntityByColumn(String column, String value,String collection, Class clazz) {
        return this.mongoTemplate.findOne(collection, new Query(where(column).is(value)),clazz);
    }

    @Override
    public T getEntityById(String collectionName, long id,Class clazz) {
        log.info("Fetching single record for id "+id +" Collection Name "+collectionName);
        return this.mongoTemplate.findOne(collectionName, new Query(where("_id").is(id)),clazz);
    }


MongoRepository

 HUMONGOUS  :)
Thanks,
Dhananjay

2 comments:

Sagar said...

Hey Dhananjay,

I'm struggling a bit to configure Spring and mongodb. Could you please help? I'm even ready to pay $ if you could help since we're competing against the time. All we need is some help in cnfiguring. the mongo part works, and has been tested via java. Let me know if you could help.

Dhananjay said...

please send me your errors / exceptions / problem statement on

dhananjay.patkar@gmail.com