MongoDB

Follow the instructions at http://docs.mongodb.org/manual/installation/ to install MongoDB on your specific operating system.

To get started with connecting to MongoDB, include the dependency for Spring Boot MongoDB starter in the pom.xml:

    <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Let's create a new Entity class Person to store to MongoDB. The following snippet shows a Person class with an ID and a name:

    public class Person {
@Id
private String id;
private String name;
public Person() {// Make JPA Happy
}
public Person(String name) {
super();
this.name = name;
}
}

We would want to store the Person entities to MongoDB. We would need to create a new repository. The following snippet shows a MongoDB repository:

    public interface PersonMongoDbRepository 
extends MongoRepository<Person, String> {
List<Person> findByName(String name);
Long countByName(String name);
}

Important things to note are as follows:

  • PersonMongoDbRepository extends MongoRepository: MongoRepository is a MongoDB-specific Repository interface
  • MongoRepository<Person, String>: We would want to store Person entities that have a key of type String
  • List<Person> findByName(String name): A simple method to find a person by name
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset