PageRenderTime 73ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/hackatravel/travelplace/daos/GenericDao.java

https://bitbucket.org/hbhackathon/travelplace
Java | 63 lines | 48 code | 15 blank | 0 comment | 3 complexity | 5b8e90706b1f0eaa76a7313ebef06db8 MD5 | raw file
  1. package com.hackatravel.travelplace.daos;
  2. import com.google.gson.Gson;
  3. import com.hackatravel.travelplace.model.ModelItem;
  4. import com.mongodb.client.FindIterable;
  5. import com.mongodb.client.MongoCollection;
  6. import com.mongodb.client.MongoDatabase;
  7. import org.bson.Document;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. public abstract class GenericDao {
  12. @Autowired
  13. protected MongoDatabase mongoDatabase;
  14. abstract MongoCollection<Document> getCollection();
  15. private Gson gson = new Gson();
  16. protected <T> void insertDocument(T object) {
  17. getCollection().insertOne(objectToDocument(object));
  18. }
  19. protected <T> List<T> getDocuments(Document query, Document sort, Class<T> clazz) {
  20. List<T> result = new ArrayList<>();
  21. FindIterable<Document> documents = getCollection().find(query);
  22. if (sort != null) {
  23. documents = documents.sort(sort);
  24. }
  25. for (Document document : documents) {
  26. String documentString = document.toJson();
  27. T object = gson.fromJson(documentString, clazz);
  28. result.add(object);
  29. }
  30. return result;
  31. }
  32. protected <T extends ModelItem> void updateDocument(T object) {
  33. getCollection().findOneAndUpdate(new Document("id", object.getId()), objectToDocument(object));
  34. }
  35. protected void deleteDocument(String id) {
  36. getCollection().deleteMany(new Document("id", id));
  37. }
  38. private <T> Document objectToDocument(T object) {
  39. String documentString = gson.toJson(object);
  40. return Document.parse(documentString);
  41. }
  42. protected Document getIdDocument(String id) {
  43. return new Document("id", id);
  44. }
  45. protected Document getEmailPasswordDocument(String email, String password) {
  46. return Document.parse("{ email: /^" + email + "$/i, password: '" + password + "' }");
  47. }
  48. }