Springboot整合MongoDB

來源:互聯網
上載者:User

標籤:編程思想   ring   啟動   auth   href   comm   fir   利用   err   

簡介

MongoDB(來自於英文單詞“Humongous”,中文含義為“龐大”)是可以應用於各種規模的企業、各個行業以及各類應用程式的開來源資料庫。作為一個適用于敏捷開發的資料庫,MongoDB的資料模式可以隨著應用程式的發展而靈活地更新。與此同時,它也為開發人員 提供了傳統資料庫的功能:二級索引,完整的查詢系統以及嚴格一致性等等。 MongoDB能夠使企業更加具有敏捷性和可擴充性,各種規模的企業都可以通過使用MongoDB來建立新的應用,提高與客戶之間的工作效率,加快產品上市時間,以及降低企業成本。

安裝mongoDB

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

建立項目

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 -->  </parent>  <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</artifactId>      <version>2.7.0</version>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-devtools</artifactId>      <scope>runtime</scope>    </dependency>    <dependency>      <groupId>org.projectlombok</groupId>      <artifactId>lombok</artifactId>      <optional>true</optional>    </dependency>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>      <scope>test</scope>    </dependency>  </dependencies>  <build>    <plugins>      <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>      </plugin>    </plugins>  </build></project>

設定檔

spring.data.mongodb.uri=mongodb://localhost:27017/demo
建立一個表/集合

一個消費者

@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; 是mongodb裡的主鍵
建立Repository

JPA的一個特性就是簡化了CRUD, 通過解析方法名實現資料的傳輸

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);}

方法名findBy欄位名即可實現查詢。

啟動並測試
@SpringBootApplicationpublic class SpringbootWithMongodbApplication implements CommandLineRunner {    private final CustomerRepository repository;    private final BookRepository bookRepository;    private final AuthorRepository 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 customers        repository.save(new Customer("Alice", "Smith", Lists.newArrayList(new Hobby("讀書", 1), new Hobby("看電影", 2))));        repository.save(new Customer("Bob", "Smith", Lists.newArrayList()));        // fetch all customers        System.out.println("Customers found with findAll():");        System.out.println("-------------------------------");        for (Customer customer : repository.findAll()) {            System.out.println(customer);        }        System.out.println();        // fetch an individual customer        System.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);        }    }}

至此,hello world完成。基本實現了mongoDB持久層的工作,只要繼續深入開發即可。

關聯表

建立一個書籍的集合

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 class Book {    @Id    private String id;    private String title;    @Field("published")    private LocalDate publicationDate;    // No args Constructor    public Book(String title, LocalDate publicationDate) {        this.title = title;        this.publicationDate = publicationDate;    }}
  • @Field指定資料庫映射的欄位
  • @Transient標註的欄位則不會映射到db
  • @Document(collection = "books")可以指定集合名稱,如果不指定則是類名首字母小寫

建立一個作者,作者擁有書籍

@Datapublic class Author {    @Id    private ObjectId id;    @Indexed(unique = true)    private String name;    @DBRef    private Set<Book> books;    // No args Constructor    public Author(String name) {        this.name = name;    }}
  • @DBRef會引用books的表
  • @Indexed(unique = true)設定索引,並且是唯一性索引
CRUD

暫時不自訂查詢了,利用內建的查詢即可

public interface AuthorRepository extends MongoRepository<Author, ObjectId> {}public interface BookRepository extends MongoRepository<Book, ObjectId> {}

測試

bookRepository.deleteAll();authorRepository.deleteAll();Book ci = new Book("Continous Integration", LocalDate.now());// id will be generated after savebookRepository.save(ci);Book c2 = new Book("Java編程思想", LocalDate.now());Book c3 = new Book("Java核心技術", LocalDate.now());Book c4 = new Book("Effective Java", LocalDate.now());Book c5 = new Book("深入理解虛擬機器", LocalDate.now());Book c6 = new Book("深入理解虛擬機器", 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());

啟動可以看到控制台輸出:

[Book(id=5b0bec767a49d017f0e46c63, title=Continous Integration, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c64, title=Java編程思想, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c65, title=Java核心技術, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c66, title=Effective Java, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c67, title=深入理解虛擬機器, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c68, title=深入理解虛擬機器, publicationDate=2018-05-28)][Author(id=5b0bec767a49d017f0e46c69, name=Julius, books=[Book(id=5b0bec767a49d017f0e46c64, title=Java編程思想, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c68, title=深入理解虛擬機器, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c67, title=深入理解虛擬機器, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c63, title=Continous Integration, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c65, title=Java核心技術, publicationDate=2018-05-28), Book(id=5b0bec767a49d017f0e46c66, title=Effective Java, publicationDate=2018-05-28)])]

串連db,查詢

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

可以自己注入MongoTemplate來實現更多操作, 比如

private final MongoTemplate mongoTemplate;List<Customer> list = mongoTemplate.findAll(Customer.class);  
索引

還可以這樣設定聯合索引

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

查詢索引

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

Springboot整合MongoDB

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.