在pom文件引入spring-boot-starter-data-mongodb依賴:java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>複製代碼
若是mongodb端口是默認端口,而且沒有設置密碼,可不配置,sprinboot會開啓默認的。spring
spring.data.mongodb.uri=mongodb://localhost:27017/springboot-db複製代碼
mongodb設置了密碼,這樣配置:mongodb
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname複製代碼
package com.forezp.entity;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public String id;
public String firstName;
public String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}複製代碼
public interface CustomerRepository extends MongoRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}複製代碼
寫一個接口,繼承MongoRepository,這個接口有了幾本的CURD的功能。若是你想自定義一些查詢,好比根據firstName來查詢,獲取根據lastName來查詢,只須要定義一個方法便可。注意firstName嚴格按照存入的mongodb的字段對應。在典型的java的應用程序,寫這樣一個接口的方法,須要本身實現,可是在springboot中,你只須要按照格式寫一個接口名和對應的參數就能夠了,由於springboot已經幫你實現了。springboot
@SpringBootApplication
public class SpringbootMongodbApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(SpringbootMongodbApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// 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);
}
}複製代碼