/SpringMongoDB/src/service/PersonService.java

https://bitbucket.org/akshayk1987/javaexamples · Java · 226 lines · 125 code · 43 blank · 58 comment · 0 complexity · ffcf781b143fe6f9017a90f695495230 MD5 · raw file

  1. package service;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.UUID;
  5. import mongo.MongoDBFactory;
  6. import org.apache.log4j.Logger;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Transactional;
  9. import com.mongodb.BasicDBObject;
  10. import com.mongodb.DBCollection;
  11. import com.mongodb.DBCursor;
  12. import com.mongodb.DBObject;
  13. import domain.Person;
  14. @Service("personService")
  15. @Transactional
  16. public class PersonService {
  17. protected static Logger logger = Logger.getLogger("service");
  18. public PersonService() {
  19. // Initialize our database
  20. init();
  21. }
  22. /**
  23. * Retrieves all persons
  24. */
  25. public List<Person> getAll() {
  26. logger.debug("Retrieving all persons");
  27. // Retrieve collection
  28. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  29. // Retrieve cursor for iterating records
  30. DBCursor cur = coll.find();
  31. // Create new list
  32. List<Person> items = new ArrayList<Person>();
  33. // Iterate cursor
  34. while(cur.hasNext()) {
  35. // Map DBOject to Person
  36. DBObject dbObject = cur.next();
  37. Person person = new Person();
  38. person.setId(dbObject.get("id").toString());
  39. person.setFirstName(dbObject.get("firstName").toString());
  40. person.setLastName(dbObject.get("lastName").toString());
  41. person.setMoney(Double.valueOf(dbObject.get("money").toString()));
  42. // Add to new list
  43. items.add(person);
  44. }
  45. // Return list
  46. return items;
  47. }
  48. /**
  49. * Retrieves a single person
  50. */
  51. public Person get( String id ) {
  52. logger.debug("Retrieving an existing person");
  53. // Retrieve collection
  54. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  55. // Create a new object
  56. DBObject doc = new BasicDBObject();
  57. // Put id to search
  58. doc.put("id", id);
  59. // Find and return the person with the given id
  60. DBObject dbObject = coll.findOne(doc);
  61. // Map DBOject to Person
  62. Person person = new Person();
  63. person.setId(dbObject.get("id").toString());
  64. person.setFirstName(dbObject.get("firstName").toString());
  65. person.setLastName(dbObject.get("lastName").toString());
  66. person.setMoney(Double.valueOf(dbObject.get("money").toString()));
  67. // Return person
  68. return person;
  69. }
  70. /**
  71. * Retrieves a single mongo object
  72. */
  73. private DBObject getDBObject( String id ) {
  74. logger.debug("Retrieving an existing mongo object");
  75. // Retrieve collection
  76. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  77. // Create a new object
  78. DBObject doc = new BasicDBObject();
  79. // Put id to search
  80. doc.put("id", id);
  81. // Find and return the mongo with the given id
  82. return coll.findOne(doc);
  83. }
  84. /**
  85. * Adds a new person
  86. */
  87. public Boolean add(Person person) {
  88. logger.debug("Adding a new user");
  89. try {
  90. // Retrieve collection
  91. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  92. // Create a new object
  93. BasicDBObject doc = new BasicDBObject();
  94. // Generate random id using UUID type 4
  95. // See http://en.wikipedia.org/wiki/Universally_unique_identifier
  96. doc.put("id", UUID.randomUUID().toString() );
  97. doc.put("firstName", person.getFirstName());
  98. doc.put("lastName", person.getLastName());
  99. doc.put("money", person.getMoney());
  100. // Save new person
  101. coll.insert(doc);
  102. return true;
  103. } catch (Exception e) {
  104. logger.error("An error has occurred while trying to add new user", e);
  105. return false;
  106. }
  107. }
  108. /**
  109. * Deletes an existing person
  110. */
  111. public Boolean delete(String id) {
  112. logger.debug("Deleting existing person");
  113. try {
  114. // Retrieve person to delete
  115. BasicDBObject item = (BasicDBObject) getDBObject( id );
  116. // Retrieve collection
  117. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  118. // Delete retrieved person
  119. coll.remove(item);
  120. return true;
  121. } catch (Exception e) {
  122. logger.error("An error has occurred while trying to delete new user", e);
  123. return false;
  124. }
  125. }
  126. /**
  127. * Edits an existing person
  128. */
  129. public Boolean edit(Person person) {
  130. logger.debug("Editing existing person");
  131. try {
  132. // Retrieve person to edit
  133. BasicDBObject existing = (BasicDBObject) getDBObject( person.getId() );
  134. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  135. // Create new object
  136. BasicDBObject edited = new BasicDBObject();
  137. // Assign existing details
  138. edited.put("id", person.getId());
  139. edited.put("firstName", person.getFirstName());
  140. edited.put("lastName", person.getLastName());
  141. edited.put("money", person.getMoney());
  142. // Update existing person
  143. coll.update(existing, edited);
  144. return true;
  145. } catch (Exception e) {
  146. logger.error("An error has occurred while trying to edit existing user", e);
  147. return false;
  148. }
  149. }
  150. private void init() {
  151. // Populate our MongoDB database
  152. logger.debug("Init MongoDB users");
  153. // Drop existing collection
  154. MongoDBFactory.getCollection("mydb","mycollection").drop();
  155. // Retrieve collection. If not existing, create a new one
  156. DBCollection coll = MongoDBFactory.getCollection("mydb","mycollection");
  157. // Create new object
  158. BasicDBObject doc = new BasicDBObject();
  159. // Generate random id using UUID type 4
  160. // See http://en.wikipedia.org/wiki/Universally_unique_identifier
  161. doc.put("id", UUID.randomUUID().toString());
  162. doc.put("firstName", "John");
  163. doc.put("lastName", "Smith");
  164. doc.put("money", 1000);
  165. coll.insert(doc);
  166. // Create new object
  167. doc = new BasicDBObject();
  168. // Generate random id using UUID type 4
  169. doc.put("id", UUID.randomUUID().toString());
  170. doc.put("firstName", "Jane");
  171. doc.put("lastName", "Adams");
  172. doc.put("money", 2000);
  173. coll.insert(doc);
  174. // Create new object
  175. doc = new BasicDBObject();
  176. // Generate random id using UUID type 4
  177. doc.put("id", UUID.randomUUID().toString());
  178. doc.put("firstName", "Jeff");
  179. doc.put("lastName", "Mayer");
  180. doc.put("money", 3000);
  181. coll.insert(doc);
  182. }
  183. }