Coder Social home page Coder Social logo

spring-guides / gs-accessing-data-mongodb Goto Github PK

View Code? Open in Web Editor NEW
132.0 34.0 161.0 1.07 MB

Accessing Data with MongoDB :: Learn how to persist data in MongoDB.

Home Page: http://spring.io/guides/gs/accessing-data-mongodb/

License: Apache License 2.0

Java 93.25% Shell 6.75%

gs-accessing-data-mongodb's Introduction

This guide walks you through the process of using Spring Data MongoDB to build an application that stores data in and retrieves it from MongoDB, a document-based database.

What You Will build

You will store Customer POJOs (Plain Old Java Objects) in a MongoDB database by using Spring Data MongoDB.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Data MongoDB.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Install and Launch MongoDB

With your project set up, you can install and launch the MongoDB database.

If you use a Mac with Homebrew, you can run the following command:

$ brew install mongodb

With MacPorts, you can run the following command:

$ port install mongodb

For other systems with package management, such as Redhat, Ubuntu, Debian, CentOS, and Windows, see the instructions at https://docs.mongodb.org/manual/installation/.

After you install MongoDB, you can launch it in a console window by running the following command (which also starts up a server process):

$ mongod

You should see output similar to the following:

all output going to: /usr/local/var/log/mongodb/mongo.log

Define a Simple Entity

MongoDB is a NoSQL document store. In this example, you store Customer objects. The following listing shows the Customer class (in src/main/java/com/example/accessingdatamongodb/Customer.java):

link:complete/src/main/java/com/example/accessingdatamongodb/Customer.java[role=include]

Here you have a Customer class with three attributes: id, firstName, and lastName. The id is mostly for internal use by MongoDB. You also have a single constructor to populate the entities when creating a new instance.

Note
In this guide, the typical getters and setters have been left out for brevity.

id fits the standard name for a MongoDB ID, so it does not require any special annotation to tag it for Spring Data MongoDB.

The other two properties, firstName and lastName, are left unannotated. It is assumed that they are mapped to fields that share the same name as the properties themselves.

The convenient toString() method prints out the details about a customer.

Note
MongoDB stores data in collections. Spring Data MongoDB maps the Customer class into a collection called customer. If you want to change the name of the collection, you can use Spring Data MongoDB’s @Document annotation on the class.

Create Simple Queries

Spring Data MongoDB focuses on storing data in MongoDB. It also inherits functionality from the Spring Data Commons project, such as the ability to derive queries. Essentially, you need not learn the query language of MongoDB. You can write a handful of methods and the queries are written for you.

To see how this works, create a repository interface that queries Customer documents, as the following listing (in src/main/java/com/example/accessingdatamongodb/CustomerRepository.java) shows:

link:complete/src/main/java/com/example/accessingdatamongodb/CustomerRepository.java[role=include]

CustomerRepository extends the MongoRepository interface and plugs in the type of values and ID that it works with: Customer and String, respectively. This interface comes with many operations, including standard CRUD operations (create, read, update, and delete).

You can define other queries by declaring their method signatures. In this case, add findByFirstName, which essentially seeks documents of type Customer and finds the documents that match on firstName.

You also have findByLastName, which finds a list of people by last name.

In a typical Java application, you write a class that implements CustomerRepository and craft the queries yourself. What makes Spring Data MongoDB so useful is the fact that you need not create this implementation. Spring Data MongoDB creates it on the fly when you run the application.

Now you can wire up this application and see what it looks like!

Create an Application Class

Spring Initializr creates a simple class for the application. The following listing shows the class that Initializr created for this example (in src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java):

link:initial/src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java[role=include]

Spring Boot automatically handles those repositories as long as they are included in the same package (or a sub-package) of your @SpringBootApplication class. For more control over the registration process, you can use the @EnableMongoRepositories annotation.

Note
By default, @EnableMongoRepositories scans the current package for any interfaces that extend one of Spring Data’s repository interfaces. You can use its basePackageClasses=MyRepository.class to safely tell Spring Data MongoDB to scan a different root package by type if your project layout has multiple projects and it does not find your repositories.

Spring Data MongoDB uses the MongoTemplate to execute the queries behind your find* methods. You can use the template yourself for more complex queries, but this guide does not cover that. (see the Spring Data MongoDB Reference Guide)

Now you need to modify the simple class that the Initializr created for you. You need to set up some data and use it to generate output. The following listing shows the finished AccessingDataMongodbApplication class (in src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java):

link:complete/src/main/java/com/example/accessingdatamongodb/AccessingDataMongodbApplication.java[role=include]

AccessingDataMongodbApplication includes a main() method that autowires an instance of CustomerRepository. Spring Data MongoDB dynamically creates a proxy and injects it there. We use the CustomerRepository through a few tests. First, it saves a handful of Customer objects, demonstrating the save() method and setting up some data to use. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findByFirstName() to fetch a single Customer by her first name. Finally, it calls findByLastName() to find all customers whose last name is Smith.

Note
By default, Spring Boot tries to connect to a locally hosted instance of MongoDB. Read the reference docs for details on pointing your application to an instance of MongoDB hosted elsewhere.

As AccessingDataMongodbApplication implements CommandLineRunner, the run method is automatically invoked when Spring Boot starts. You should see something like the following (with other output, such as queries, as well):

== Customers found with findAll():
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

== Customer found with findByFirstName('Alice'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
== Customers found with findByLastName('Smith'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

Summary

Congratulations! You set up a MongoDB server and wrote a simple application that uses Spring Data MongoDB to save objects to and fetch them from a database, all without writing a concrete repository implementation.

Note
If you want to expose MongoDB repositories with a hypermedia-based RESTful front end with little effort, read Accessing MongoDB Data with REST.

gs-accessing-data-mongodb's People

Contributors

basiraventuro avatar bclozel avatar btalbott avatar buzzardo avatar cbeams avatar elnur avatar gregturn avatar jotafeldmann avatar mp911de avatar robertmcnees avatar royclarkson avatar sdeleuze avatar snicoll avatar spring-operator avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gs-accessing-data-mongodb's Issues

LocalDate handling is not working well

I have added two fields to the complete version:

public LocalDate birthdate;
public TreeMap<LocalDate, Double> dateValues;

The customer gets saved like this:

{
"_id" : ObjectId("5c0918435deea55a9522cecd"),
"firstName" : "Oliver August",
"lastName" : "Matthews",
"birthdate" : ISODate("2018-12-05T23:00:00.000Z"),
"dateValues" : {
"2018-12-05" : 43.0,
"2018-12-06" : 42.0
},
"_class" : "hello.Customer"
}

After that reading is not working any more: No converter found capable of converting from type [java.lang.String] to type [java.time.LocalDate]

You can see it here: https://github.com/puskai/gs-accessing-data-mongodb

How can I return fields like this find({},{"field1.field2":1})

The query : db.getCollection('homework').find({},{"field1.field2":1}) work well in robomongo.
When I use spring @query like this:
@query(value = "{}", fields="{ ?0 : 1}")
public List findByDoRecordKey(String key); // key is "field1.field2"

It is not work well. And it works like:
db.getCollection('homework').find({},{"field1":1})
removed the field2.

Accessing Data with MongoDB article needs improvements

The startup guide at Accessing Data with MongoDB requires some improvements. For example, there is no place for this paragraph in the write-up:

Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

This is because that write-up is not about serving HTTP requests. It has nothing to do with serving content to the user. And there is no Spring boot starter web dependency on the classpath of the article.

Instead, it should be replaced with something like this:

Spring boot application will automatically enable @EnableMongoRepositories if it finds spring-boot-starter-data-mongodb on the classpath.

Something like that.

Request : Add Connection settings

Request : Please add annotations or appication properties for typical connection settings when connecting to a MongoDb hosted on a different system - ports, IP, user name ... thanks

SpringBoot DataJpa

Most important thing is Student_tbl is creating a table in Database(oracle) but where as Data is not inserting into the Table....

2019-02-07 10:14:14.336 INFO 9900 --- [ main] i.i.A.StudentSpringBootApplication : Starting StudentSpringBootApplication on ACHYUTH with PID 9900 (D:\SpringToolSuit\StudentSpringBoot\target\classes started by Achyuth in D:\SpringToolSuit\StudentSpringBoot)
2019-02-07 10:14:14.336 INFO 9900 --- [ main] i.i.A.StudentSpringBootApplication : No active profile set, falling back to default profiles: default
2019-02-07 10:14:14.961 INFO 9900 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-02-07 10:14:14.977 INFO 9900 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16ms. Found 0 repository interfaces.
2019-02-07 10:14:15.534 INFO 9900 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-02-07 10:14:16.270 INFO 9900 --- [ main] com.zaxxer.hikari.pool.PoolBase : HikariPool-1 - Driver does not support get/set network timeout for connections. (oracle.jdbc.driver.T4CConnection.getNetworkTimeout()I)
2019-02-07 10:14:16.285 INFO 9900 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-02-07 10:14:16.348 INFO 9900 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-02-07 10:14:16.473 INFO 9900 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2019-02-07 10:14:16.473 INFO 9900 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-02-07 10:14:16.754 INFO 9900 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-02-07 10:14:16.982 INFO 9900 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
2019-02-07 10:14:17.144 INFO 9900 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [byte[]] overrides previous : org.hibernate.type.BinaryType@15fb7a32
2019-02-07 10:14:17.144 INFO 9900 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [[B] overrides previous : org.hibernate.type.BinaryType@15fb7a32
2019-02-07 10:14:17.144 INFO 9900 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [Byte[]] overrides previous : org.hibernate.type.WrapperBinaryType@57adfab0
2019-02-07 10:14:17.144 INFO 9900 --- [ main] org.hibernate.type.BasicTypeRegistry : HHH000270: Type registration [[Ljava.lang.Byte;] overrides previous : org.hibernate.type.WrapperBinaryType@57adfab0
2019-02-07 10:14:18.174 INFO 9900 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-02-07 10:14:18.218 WARN 9900 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'info.inetsolv.repo.StudentRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2019-02-07 10:14:18.218 INFO 9900 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-02-07 10:14:18.234 INFO 9900 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2019-02-07 10:14:18.234 INFO 9900 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2019-02-07 10:14:18.250 INFO 9900 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-02-07 10:14:18.422 ERROR 9900 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Field repository in info.inetsolv.service.StudentService required a bean of type 'info.inetsolv.repo.StudentRepository' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'info.inetsolv.repo.StudentRepository' in your configuration.

Getting error - Field repository in hello.Application required a bean of type 'hello.CustomerRepository' that could not be found.

Thanks very nice tutorial.

I have cloned the project and when trying to nun Application.java as SpringBoot application gets the below error.
CustomerRepositoryTests.java also gives the same error.

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

2017-10-15 21:24:07.546 INFO 819 --- [ main] hello.Application : Starting Application on Jayakumars-iMac with PID 819 (/Users/jay/git/gs-accessing-data-mongodb/complete/target/classes started by jay in /Users/jay/git/gs-accessing-data-mongodb/complete)
2017-10-15 21:24:07.547 INFO 819 --- [ main] hello.Application : No active profile set, falling back to default profiles: default
2017-10-15 21:24:07.571 INFO 819 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@23bb8443: startup date [Sun Oct 15 21:24:07 BST 2017]; root of context hierarchy
2017-10-15 21:24:07.806 WARN 819 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'application': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'hello.CustomerRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-10-15 21:24:07.810 INFO 819 --- [ main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-10-15 21:24:07.867 ERROR 819 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Field repository in hello.Application required a bean of type 'hello.CustomerRepository' that could not be found.

Action:

Consider defining a bean of type 'hello.CustomerRepository' in your configuration.

Mongo Health Indicator is showing UncategorizedMongoDbException

Hi team,

We have used the custom MongoConfiguration by extending the AbstractMongoConfiguration in our application. We have configured the below properties.

We have used Spring Boot 2.0.1.RELEASE, Spring data Mongo 2.0.6.RELEASE

mongo.connection.timeout=2000
mongo.socket.timeout=5000
mongo.server.selection.time=2000
mongo.max.connection.per.host=100
mongo.client.thread.allowed=4
mongo.max.wait.time=2000
mongo.connection.uri=mongodb://localhost:27017/testDB?serverSelectionTimeoutMS=2000&connectTimeoutMS=2000&maxIdleTimeMS=15000&maxLifeTimeMS=600000
mongo.db.name=testDB
mongo.client.read.concern=LOCAL
mongo.client.write.concern=1
mongo.client.write.timeout=5000
mongo.write.concern.journal=true
mongo.write.timeout.unit=MILLISECONDS
mongo.client.read.preference=PRIMARY
cache.expire.time=3600000

But getting the below exception for the mongo health check monitor.
Not sure what may be causing this:


org.springframework.boot.actuate.mongo.MongoHealthIndicator:89 - MongoDB health check failed
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception sending message; nested exception is com.mongodb.MongoSocketWriteException: Exception sending message
         at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:131) ~[spring-data-mongodb-2.0.7.RELEASE.jar!/:2.0.7.RELEASE]
         at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2589) ~[spring-data-mongodb-2.0.7.RELEASE.jar!/:2.0.7.RELEASE]
         at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:499) ~[spring-data-mongodb-2.0.7.RELEASE.jar!/:2.0.7.RELEASE]
         at org.springframework.data.mongodb.core.MongoTemplate.executeCommand(MongoTemplate.java:403) ~[spring-data-mongodb-2.0.7.RELEASE.jar!/:2.0.7.RELEASE]
         at org.springframework.boot.actuate.mongo.MongoHealthIndicator.doHealthCheck(MongoHealthIndicator.java:46) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:84) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:68) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.health.HealthEndpointWebExtension.getHealth(HealthEndpointWebExtension.java:50) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at sun.reflect.GeneratedMethodAccessor101.invoke(Unknown Source) ~[?:?]
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_161]
         at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_161]
         at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:223) ~[spring-core-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.boot.actuate.endpoint.invoke.reflect.ReflectiveOperationInvoker.invoke(ReflectiveOperationInvoker.java:76) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.endpoint.annotation.AbstractDiscoveredOperation.invoke(AbstractDiscoveredOperation.java:61) ~[spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$ServletWebOperationAdapter.handle(AbstractWebMvcEndpointHandlerMapping.java:243) [spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(AbstractWebMvcEndpointHandlerMapping.java:299) [spring-boot-actuator-2.0.2.RELEASE.jar!/:2.0.2.RELEASE]
         at sun.reflect.GeneratedMethodAccessor100.invoke(Unknown Source) ~[?:?]
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_161]
         at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_161]
         at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) [spring-web-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) [spring-webmvc-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877) [spring-webmvc-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783) [spring-webmvc-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]
         at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) [spring-webmvc-5.0.6.RELEASE.jar!/:5.0.6.RELEASE]


Not able to find out what may be causing this exception. Please suggest how to resolve this.

Regards,
Vivek

Upgrade Spring Boot to the latest version

Update the guide to use the most recent Spring Boot version.

Files that require changes are:

initial/build.gradle
initial/pom.xml
complete/build.gradle
complete/pom.xml

Could you help tell me how can I modify the mongo db server connection info?

Hi:
Follow the example, default mongo connection is localhost:27017, but I have standalone mongo server, so how can I modify the mongo db server connection info?

PS: I am using spring core not spring-boot, so I have to manually initailize mongo info, I am using Java config instead of xml config, could you help tell me how to use @EnableMongoRepositories, do you have some examples? appreciated! thanks!

This package does not compile

I am getting the following error on running the complete package:

2017-06-11 12:54:12.973 INFO 25961 --- [ main] org.mongodb.driver.cluster : No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}]}. Waiting for 30000 ms before timing out

I suspect it is related to this stackoverflow post: https://stackoverflow.com/questions/31933821/cant-connect-to-local-monogodb-from-java.

So essentially your code has a race condition between the mongodb database and the code (which is an error that is not always reproducible, as it depends on the speed and operating environment of the users computer). I have had the same issue with your other mongodb tutorial and so will be opening an issue there as well. It looks like to solve this it will require a refactor, but as I am new to java it is something that I cannot do on my own. Please fix!

With server 4.0, are you able to get the `@Transactional` working?

Hi, have you tried out the transactional support with the Cosmos DB API for MongoDB v4.0? I have already updated our server to 4.0, and have the MongoTransactionManager bean setup, and applied the @Transactional to the method. But I don't see anything happen. the record still being inserted and no rollback happens when an error happens.

The same code I can get it working in a pure MongoDB 4.x server

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.