'Mongodb loosing connection after every 1 request in springboot

MongoDB is losing connection after every request. There is no entity class. I am connecting with MongoDB with URL.

This is the configuration for MongoDB which I am using.

private static String uri = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false";
    private static com.mongodb.client.MongoClient mongoClient = MongoClients.create(uri);




This is one of the requests 


 public static int getComponentIdFromName(String script_name, Integer Project_Id) {
    
            db = mongoClient.getDatabase("qtaf");
    
            collection = db.getCollection("component");
    
            Document data = null;
            int componentId = -1;
            try {
                whereQuery.put("Component_Name", script_name);
                whereQuery.put("Project_Id", Project_Id);
                FindIterable<Document> iterDoc = collection.find(whereQuery);
                Iterator<Document> it = iterDoc.iterator();
    
                if (it.hasNext()) {
                    data = it.next();
                    componentId = (int) data.get("Component_Id");
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println("Error while getting component id from scipt name");
            }
            return componentId;
        }

I am getting the required output in this request but after refreshing the page output does not persists. Any other request with other Api's also does not work. I have to restart the service in the spring boot for each request.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source