Advertisement
Guest User

Untitled

a guest
Nov 28th, 2014
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package dao;
  2.  
  3. import util.InstanceFactory;
  4.  
  5. import com.mongodb.DB;
  6. import com.mongodb.MongoClient;
  7. import org.apache.log4j.Logger;
  8.  
  9. public class MongoConnector {
  10.  
  11. private static MongoConnector mongoConnectorInstance;
  12.  
  13. private DB DbConnection;
  14.  
  15. public static DB getConnection(String dbName) {
  16.  
  17. MongoConnector.mongoConnectorInstance = InstanceFactory.instantiateAsSingleton(MongoConnector.class);
  18.  
  19. if (MongoConnector.mongoConnectorInstance.DbConnection == null) {
  20.  
  21. synchronized (MongoConnector.mongoConnectorInstance) {
  22.  
  23. if (MongoConnector.mongoConnectorInstance.DbConnection == null) {
  24. MongoConnector.mongoConnectorInstance.DbConnection = MongoConnector.mongoConnectorInstance
  25. .getDbConnection(dbName);
  26. }
  27. }
  28. }
  29.  
  30. return MongoConnector.mongoConnectorInstance.DbConnection;
  31.  
  32. }
  33.  
  34. private DB getDbConnection(String dbName) {
  35.  
  36. DB db = null;
  37.  
  38. try {
  39.  
  40. MongoClient mongoClient = new MongoClient("some ip address of mongos", 27017);
  41.  
  42. // Now connect to your databases
  43. db = mongoClient.getDB(dbName);
  44.  
  45. System.out.println("Connect to database successfully");
  46.  
  47. } catch (Exception e) {
  48. System.err.println(e.getClass().getName() + ": " + e.getMessage());
  49. }
  50.  
  51. return db;
  52. }
  53. }
  54.  
  55. public static boolean insert(DBObject object, String table) {
  56. boolean status = false;
  57. if (object != null) {
  58. try {
  59. DB db = MongoConnector.getConnection("somedb");
  60. DBCollection collection = db.getCollection(table);
  61. //System.out.println(collection);
  62. if (collection == null) {
  63. db.createCollection(table, null);
  64. }
  65. collection.insert(object);
  66. status = true;
  67. } catch (Exception e) {
  68. MongoDao.logger.error("Could not insert in database" + e);
  69. }
  70. }
  71. return status;
  72. }
  73.  
  74. DBobject o=new BasicDBObject("SomeColumn":"somevalue")
  75. .append("shardKey":"UP");
  76. MongoDAO.insert(o,"sometable");
  77.  
  78. DBobject o = new BasicDBObject("SomeColumn" : "somevalue")
  79. .append("shardKey" : "UP");
  80.  
  81. DBobject o = new BasicDBObject("SomeColumn" : "somevalue")
  82. .append("State" : "UP");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement