GithubHelp home page GithubHelp logo

buzzardo / gs-accessing-data-mongodb Goto Github PK

View Code? Open in Web Editor NEW

This project forked from spring-guides/gs-accessing-data-mongodb

0.0 1.0 0.0 993 KB

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

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

Java 93.03% Shell 6.97%

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

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs only the Spring Data MongoDB dependency. The following image shows the Initializr set up for this sample project:

initializr
Note
The preceding image shows the Initializr with Maven chosen as the build tool. You can also use Gradle. It also shows values of com.example and accessing-data-mongodb as the Group and Artifact, respectively. You will use those values throughout the rest of this sample.

The following listing shows the pom.xml file created when you choose Maven:

link:complete/pom.xml[role=include]

The following listing shows the build.gradle file created when you choose Gradle:

link:complete/build.gradle[role=include]

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 royclarkson avatar snicoll avatar spring-operator avatar

Watchers

 avatar

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.