Searching...
Tuesday, 19 November 2013

Spring Data Mongodb : How to make readonly database

09:12

In java Mongodb driver package com.mongodb.DB setReadOnly(boolean ) method provides options to make mongodb database as readonly. In this example we will see how to use this.

Example

package com.pretech;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.Mongo;
public class SpringDataReadOnly {
	public static void main(String[] args) {
		Mongo mongo;
		try {
			mongo = new Mongo("localhost");
			MongoTemplate mongoTemplate = new MongoTemplate(mongo, "SampleDb");
			mongoTemplate.getDb().setReadOnly(true);
			// Insert customer details
			mongoTemplate.save(new Customer("Ramu"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
class Customer {
	private String name;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Customer(String name) {
		super();
		this.name = name;
	}
}

Output



java.lang.IllegalStateException: db is read only
    at com.mongodb.DBCollection.checkReadOnly(DBCollection.java:1143)
    at com.mongodb.DBCollection.save(DBCollection.java:611)
    at com.mongodb.DBCollection.save(DBCollection.java:599)
    at org.springframework.data.mongodb.core.MongoTemplate$10.doInCollection(MongoTemplate.java:874)
    at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:401)


0 comments: