Springboot Integrated MongoDB

Source: Internet
Author: User

Brief introduction

MongoDB (from the English word "humongous", the Chinese meaning "huge") is an open-source database that can be applied to businesses of all sizes, industries and applications. As a database for agile development, MongoDB's data schema can be updated flexibly as the application progresses. At the same time, it also provides developers with the functionality of traditional databases: two-level indexes, a complete query system, and strict consistency, among other things. MongoDB enables businesses to be more agile and scalable, and businesses of all sizes can use MongoDB to create new applications, increase productivity with their customers, accelerate time-to-market, and reduce enterprise costs.

Installing MongoDB

Https://www.cnblogs.com/woshimrf/p/linux-install-mongodb.html

Create a project

Https://github.com/Ryan-Miao/springboot-with-mongodb

Pom

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http ://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.test </groupId> <artifactId>springboot-with-mongodb</artifactId> <version>0.0.1-snapshot</ Version> <packaging>jar</packaging> <name>springboot-with-mongodb</name> < Description>demo Project for Spring boot</description> <parent> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-starter-parent</artifactId> < Version>2.0.2.release</version> <relativePath/> <!--lookup parent from repository to </paren T> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <Project.reporting.outputencoding>utf-8</project.reporting.outputencoding> <java.version>1.8</ java.version> </properties> <dependencies> <dependency> <groupid>org.springframework.    Boot</groupid> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter      -web</artifactid> </dependency> <dependency> <groupId>io.springfox</groupId>     <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactid>springfox-swagger-ui</ar tifactid> <version>2.7.0</version> </dependency> <dependency> <groupid>or G.springframework.boot</groupid> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </depen dency> <dependency> <groupId>org.projectlombok</groupId> <artifactid>lombok</ar tifactid> <optional>true</optional> </dependency> <dependency> <groupid>o Rg.springframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <scope&        gt;test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plugin</artif actid> </plugin> </plugins> </build></project>

Configuration file

spring.data.mongodb.uri=mongodb://localhost:27017/demo
Create a Table/collection

A consumer

@Datapublic class Customer {    @Id    public String id;    public String firstName;    public String lastName;    private List<Hobby> hobbies;    public Customer() {    }    public Customer(String firstName, String lastName, List<Hobby> hobbies) {        this.firstName = firstName;        this.lastName = lastName;        this.hobbies = hobbies;    }}
    • import org.springframework.data.annotation.Id;It's the primary key in MongoDB.
Create repository

One of the features of JPA is that it simplifies crud by parsing the method name for data transfer

import com.test.springbootwithmongodb.entity.Customer;import java.util.List;import org.springframework.data.mongodb.repository.MongoRepository;public interface CustomerRepository extends MongoRepository<Customer, String> {    Customer findByFirstName(String firstName);    List<Customer> findByLastName(String lastName);}

Method name to findBy字段名 implement the query.

Start and test
@SpringBootApplication Public classSpringbootwithmongodbapplicationImplementsCommandlinerunner {Private FinalCustomerrepository repository;Private FinalBookrepository bookrepository;Private FinalAuthorrepository authorrepository;@Autowired     Public springbootwithmongodbapplication(Customerrepository repository, bookrepository bookrepository, Authorrepository authorrepository) { This.Repository= Repository; This.bookrepository= Bookrepository; This.authorrepository= Authorrepository; } Public Static void Main(string[] args) {springapplication.Run(Springbootwithmongodbapplication.class, args); }@Override     Public void Run(String... args) {repository.DeleteAll();//Save a couple of customersRepository.Save(New Customer("Alice","Smith", Lists.newarraylist(New Hobby("reading",1),New Hobby("See the movie",2)))); Repository.Save(New Customer("Bob","Smith", Lists.newarraylist()));//Fetch All CustomersSystem. out.println("Customers found with FindAll ():"); System. out.println("-------------------------------"); for(Customer customer:repository.FindAll()) {System. out.println(customer); } System. out.println();//Fetch an individual customerSystem. out.println("Customer found with Findbyfirstname (' Alice '):"); System. out.println("--------------------------------"); System. out.println(repository.Findbyfirstname("Alice")); System. out.println("Customers found with Findbylastname (' Smith '):"); System. out.println("--------------------------------"); for(Customer customer:repository.Findbylastname("Smith")) {System. out.println(customer); }    }}

At this point, Hello World is complete. The basic implementation of the MongoDB persistence layer of work, as long as the further development can be.

Association tables

Create a collection of books

import java.time.LocalDate;import Lombok. Data;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;import Org.springframework.data.mongodb.core.mapping.Field;@Data@Document(Collection ="Books") Public classBook {@Id    PrivateString ID;PrivateString title;@Field("published")PrivateLocaldate publicationdate;//No args Constructor     PublicBook (String title, Localdate publicationdate) { This.title= title; This.publicationdate= Publicationdate; }}
    • @FieldSpecify fields for database mappings
    • @TransientThe labeled fields are not mapped to the DB
    • @Document(collection = "books")You can specify the collection name if you do not specify the first letter of the class name lowercase

Create an author with a book

@Datapublicclass Author {    @Id    private ObjectId id;    @Indexedtrue)    private String name;    @DBRef    private Set<Book> books;    // No args Constructor    publicAuthor(String name) {        this.name = name;    }}
    • @DBRefWill refer to the books table
    • @Indexed(unique = true)Sets the index and is a unique index
Crud

The query is not customized, using the built-in query can

publicinterfaceextends MongoRepository<Author, ObjectId> {}publicinterfaceextends MongoRepository<Book, ObjectId> {}

Test

Bookrepository.DeleteAll(); Authorrepository.DeleteAll(); Book CI =NewBook ("Continous integration", Localdate. Now());//ID would is generated after saveBookrepository.Save(CI); Book C2 =NewBook ("Java Programming ideas", Localdate. Now()); Book C3 =NewBook ("Java Core technology", Localdate. Now()); Book C4 =NewBook ("Effective Java", Localdate. Now()); Book C5 =NewBook ("In-depth understanding of virtual machines", Localdate. Now()); Book C6 =NewBook ("In-depth understanding of virtual machines", Localdate. Now()); bookrepository.Save(C2); bookrepository.Save(C3); bookrepository.Save(C4); bookrepository.Save(C5); bookrepository.Save(C6); list<book> books = Bookrepository.FindAll(); System. out.println(books); Author Julius =New Author("Julius"); Julius.Setbooks(Stream. of(CI, C2, C3, C4, C5, C6).Collect(Collectors.Toset())); Authorrepository.Save(Julius); System. out.println(Authorrepository.FindAll());

Start to see the console output:

[Book (Id=5b0bec767a49d017f0e46c63, title=continous integration, publicationdate=2018-05-28), book (id= 5B0BEC767A49D017F0E46C64, Title=java programming ideas, publicationdate=2018-05-28), book (Id=5b0bec767a49d017f0e46c65, title= Java core Technology, PUBLICATIONDATE=2018-05-28), book (ID=5B0BEC767A49D017F0E46C66, title=effective Java, publicationdate= 2018-05-28), Book (id=5b0bec767a49d017f0e46c67, title= in-depth understanding of virtual machines, publicationdate=2018-05-28), book (id= 5b0bec767a49d017f0e46c68, title= in-depth understanding of virtual machines, publicationdate=2018-05-28)][author (id=5b0bec767a49d017f0e46c69, name= Julius, Books=[book (ID=5B0BEC767A49D017F0E46C64, Title=java programming Idea, publicationdate=2018-05-28), book (id= 5b0bec767a49d017f0e46c68, title= in-depth understanding of virtual machines, publicationdate=2018-05-28), book (Id=5b0bec767a49d017f0e46c67, title= In-depth understanding of virtual machines, publicationdate=2018-05-28), book (Id=5b0bec767a49d017f0e46c63, title=continous integration, publicationdate=2018-05-28), Book (ID=5B0BEC767A49D017F0E46C65, Title=java core Technology, PUBLICATIONDATE=2018-05-28), book ( ID=5B0BEC767A49D017F0E46C66, Title=effectIve (Java, publicationdate=2018-05-28)])] 

Connect db, Query

db.author.find({}){     "_id" : ObjectId("5b0bec767a49d017f0e46c69"),     "name" : "Julius",     "books" : [        DBRef("books", ObjectId("5b0bec767a49d017f0e46c64")),         DBRef("books", ObjectId("5b0bec767a49d017f0e46c68")),         DBRef("books", ObjectId("5b0bec767a49d017f0e46c67")),         DBRef("books", ObjectId("5b0bec767a49d017f0e46c63")),         DBRef("books", ObjectId("5b0bec767a49d017f0e46c65")),         DBRef("books", ObjectId("5b0bec767a49d017f0e46c66"))    ],     "_class" : "com.test.springbootwithmongodb.entity.Author"}
Mongotemplate

You can inject mongotemplate yourself to do more, such as

privatefinal MongoTemplate mongoTemplate;List<Customer> list = mongoTemplate.findAll(Customer.class);  
Index

You can also set a federated index like this

@Document@CompoundIndexes({    @CompoundIndex(name = "email_age", def = "{'email.id' : 1, 'age': 1}")})public class User {    //}

Query index

db.user.getIndexes();{    "v" : 1,    "key" : {        "email.id" : 1,        "age" : 1    },    "name" : "email_age",    "ns" : "test.user"}

Springboot Integrated MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.