/src/main/java/com/hackatravel/travelplace/daos/GenericDao.java
Java | 63 lines | 48 code | 15 blank | 0 comment | 3 complexity | 5b8e90706b1f0eaa76a7313ebef06db8 MD5 | raw file
- package com.hackatravel.travelplace.daos;
- import com.google.gson.Gson;
- import com.hackatravel.travelplace.model.ModelItem;
- import com.mongodb.client.FindIterable;
- import com.mongodb.client.MongoCollection;
- import com.mongodb.client.MongoDatabase;
- import org.bson.Document;
- import org.springframework.beans.factory.annotation.Autowired;
- import java.util.ArrayList;
- import java.util.List;
- public abstract class GenericDao {
- @Autowired
- protected MongoDatabase mongoDatabase;
- abstract MongoCollection<Document> getCollection();
- private Gson gson = new Gson();
- protected <T> void insertDocument(T object) {
- getCollection().insertOne(objectToDocument(object));
- }
- protected <T> List<T> getDocuments(Document query, Document sort, Class<T> clazz) {
- List<T> result = new ArrayList<>();
- FindIterable<Document> documents = getCollection().find(query);
- if (sort != null) {
- documents = documents.sort(sort);
- }
- for (Document document : documents) {
- String documentString = document.toJson();
- T object = gson.fromJson(documentString, clazz);
- result.add(object);
- }
- return result;
- }
- protected <T extends ModelItem> void updateDocument(T object) {
- getCollection().findOneAndUpdate(new Document("id", object.getId()), objectToDocument(object));
- }
- protected void deleteDocument(String id) {
- getCollection().deleteMany(new Document("id", id));
- }
- private <T> Document objectToDocument(T object) {
- String documentString = gson.toJson(object);
- return Document.parse(documentString);
- }
- protected Document getIdDocument(String id) {
- return new Document("id", id);
- }
- protected Document getEmailPasswordDocument(String email, String password) {
- return Document.parse("{ email: /^" + email + "$/i, password: '" + password + "' }");
- }
- }