0

Using MongoDB with Java

Please note this cutom query is only made to see how it functions ,so please don' t tell me there are alternatives in hibernate (I already know that ,I just want to run it)

Error

Exception in thread "main" java.lang.NullPointerException
    at repository.serviceclass.getjsondatamongo(serviceclass.java:25)
    at springbootwebsocketexample.SpringBootWebsocketExampleApplication.main(SpringBootWebsocketExampleApplication.java:58)

For UR HELP (serviceclass.java:25) == return userrep2.obj1(); SpringBootWebsocketExampleApplication.java:58=== JSONObject jsOn1=cc1.getjsondatamongo();

Here is my repository.UserRepository.java

package repository;

import java.util.ArrayList;
import java.util.*;
import org.json.*;

//import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.*;

import com.mongodb.connection.*;
import document.Users;
public interface UserRepository extends MongoRepository<Users,Integer> {




    @Query("db.users.find()")
    JSONObject obj1(); 
}

Here is my repository.serviceclass

package repository;

import java.util.*;

import org.json.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import document.*;
@Service
public class serviceclass {
    @Autowired
    UserRepository userrep2;
    public JSONObject getjsondatamongo()
    {
        return userrep2.obj1();
    }
}

Here is my SpringBootWebsocketExampleApplication.java

package springbootwebsocketexample;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;
import repository.*;
import document.Users;
import repository.*;

import java.awt.*;
import java.util.*;
import java.util.List;

import org.json.*;
@SpringBootApplication
@ComponentScan(basePackages= {"resource"})
@ComponentScan(basePackages= {"document"})
@ComponentScan(basePackages= {"repository"})
@ComponentScan(basePackages= {"config"})
public class SpringBootWebsocketExampleApplication implements CommandLineRunner {

    @Autowired
    public serviceclass cc1 ;
    public static void main(String[] args) {


        SpringApplication.run(SpringBootWebsocketExampleApplication.class, args);

    }


      @Override
        public void run(String... args) throws Exception {
             List<Users> kk=new ArrayList<Users>();
             JSONObject jsOn1=cc1.getjsondatamongo();
             System.out.println(jsOn1);
        }
}

UPDATION I HAVE UPDATED MY SpringBootWebsocketExampleApplication.java above New Error = Caused by: com.mongodb.util.JSONParseException: db.users.find()

15:45:36.951 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
15:45:36.954 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
15:45:36.954 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/vaibhav.chhabra/Documents/workspace-sts-3.9.7.RELEASE/DB_Mongo_exapme_name/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2019-02-12 15:45:37.110  INFO 3048 --- [  restartedMain] s.SpringBootWebsocketExampleApplication  : Starting SpringBootWebsocketExampleApplication on VNL-VaibhavC with PID 3048 (C:\Users\vaibhav.chhabra\Documents\workspace-sts-3.9.7.RELEASE\DB_Mongo_exapme_name\target\classes started by vaibhav.chhabra in C:\Users\vaibhav.chhabra\Documents\workspace-sts-3.9.7.RELEASE\DB_Mongo_exapme_name)
2019-02-12 15:45:37.110  INFO 3048 --- [  restartedMain] s.SpringBootWebsocketExampleApplication  : No active profile set, falling back to default profiles: default
2019-02-12 15:45:37.150  INFO 3048 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1599273b: startup date [Tue Feb 12 15:45:37 IST 2019]; root of context hierarchy
2019-02-12 15:45:38.032  INFO 3048 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-02-12 15:45:38.038  INFO 3048 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-02-12 15:45:38.039  INFO 3048 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2019-02-12 15:45:38.089  INFO 3048 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-02-12 15:45:38.089  INFO 3048 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 941 ms
2019-02-12 15:45:38.183  INFO 3048 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-02-12 15:45:38.185  INFO 3048 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-02-12 15:45:38.186  INFO 3048 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-02-12 15:45:38.186  INFO 3048 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-02-12 15:45:38.186  INFO 3048 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-02-12 15:45:38.448  INFO 3048 --- [  restartedMain] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-02-12 15:45:38.448  INFO 3048 --- [  restartedMain] org.mongodb.driver.cluster               : Adding discovered server localhost:27017 to client view of cluster
2019-02-12 15:45:38.489  INFO 3048 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:225}] to localhost:27017
2019-02-12 15:45:38.490  INFO 3048 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, roundTripTimeNanos=459434}
2019-02-12 15:45:38.491  INFO 3048 --- [localhost:27017] org.mongodb.driver.cluster               : Discovered cluster type of STANDALONE
2019-02-12 15:45:38.622  WARN 3048 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootWebsocketExampleApplication': Unsatisfied dependency expressed through field 'cc1'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceclass': Unsatisfied dependency expressed through field 'userrep2'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
db
^
2019-02-12 15:45:38.626  INFO 3048 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-02-12 15:45:38.634  INFO 3048 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2019-02-12 15:45:38.641 ERROR 3048 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootWebsocketExampleApplication': Unsatisfied dependency expressed through field 'cc1'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceclass': Unsatisfied dependency expressed through field 'userrep2'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
db
^
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at springbootwebsocketexample.SpringBootWebsocketExampleApplication.main(SpringBootWebsocketExampleApplication.java:65) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_201]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.10.RELEASE.jar:1.5.10.RELEASE]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceclass': Unsatisfied dependency expressed through field 'userrep2'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
db
^
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 24 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: 
db
^
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 37 common frames omitted
Caused by: com.mongodb.util.JSONParseException: 
db
^
    at com.mongodb.util.JSONParser.parse(JSON.java:230) ~[mongodb-driver-3.4.3.jar:na]
    at com.mongodb.util.JSONParser.parse(JSON.java:155) ~[mongodb-driver-3.4.3.jar:na]
    at com.mongodb.util.JSON.parse(JSON.java:92) ~[mongodb-driver-3.4.3.jar:na]
    at com.mongodb.util.JSON.parse(JSON.java:73) ~[mongodb-driver-3.4.3.jar:na]
    at org.springframework.data.mongodb.repository.query.StringBasedMongoQuery$ParameterBindingParser.parseAndCollectParameterBindingsFromQueryIntoBindings(StringBasedMongoQuery.java:230) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]
    at org.springframework.data.mongodb.repository.query.StringBasedMongoQuery.<init>(StringBasedMongoQuery.java:93) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]
    at org.springframework.data.mongodb.repository.query.StringBasedMongoQuery.<init>(StringBasedMongoQuery.java:72) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactory$MongoQueryLookupStrategy.resolveQuery(MongoRepositoryFactory.java:169) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:449) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:222) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean.afterPropertiesSet(MongoRepositoryFactoryBean.java:117) ~[spring-data-mongodb-1.10.10.RELEASE.jar:na]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 47 common frames omitted

2
  • @Pijotrek I did them both still no effect Commented Feb 12, 2019 at 9:40
  • I deleted my comment and put an answer, please try it and tell if it worked Commented Feb 12, 2019 at 9:45

1 Answer 1

1

Annotate your repository class with @Repository.

Also, do not do that:

ServiceClass cc1 = new ServiceClass();

instead, this should be injected with @Autowired annotation to let Spring framework do its job, like this:

public class SpringBootWebsocketExampleApplication implements CommandLineRunner {

    @Autowired
    private ServiceClass serviceClass;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebsocketExampleApplication.class, args);

    }

    @Override
    public void run(String... args) throws Exception {
         List<Users> kk=new ArrayList<Users>();
         JSONObject jsOn1=cc1.getjsondatamongo();
         System.out.println(jsOn1);
    }

}

This is the spring approach. Additional reading: https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring

And a small piece of advice: follow naming conventions/standards. Classes should be named with a capital letter, camel cased, i.e. UserRepository, UserService

part2:

Assuming from your newer/current exception. I think there is a problem with parsing the query result into JSONObject. I am not sure about this but usually you want to return list of POJOs, i.e: List<User>.

Also, you could probably use "built in" methods such as findAll() - no need to use native query here. Try this:

@Service
public class ServiceClass {
    @Autowired
    UserRepository userRepository;
    public JSONObject getjsondatamongo()
    {
        return userRepository.findAll();
    }
}

part3

Going through some internet tutorials and reading docs, I think you should simply ommit db.collection.find() and just provide {} in your @Query. Like @Query("{}") if you want to have the whole data returned.

Sign up to request clarification or add additional context in comments.

12 Comments

Well Anotation is not allowed in the main class , no idea why it is so ,it says " The annotation @Autowired is disallowed for this location"
are you sure you are using it in correct place? It should be used for field, not inside the main method.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springBootWebsocketExampleApplication': Unsatisfied dependency expressed through field 'cc1'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceclass': Unsatisfied dependency expressed through field 'userrep2'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is com.mongodb.util.JSONParseException: db.users.find()
Ok, another problem but we are 1 step closer. Could you edit your post with current stacktrace please?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.