1、pom.xml 中添加mongodb依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、写一个Customer 实体类
package com.example.jdbc.jpa.model;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
private String id;
private String firstName;
private String lastName;
protected 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);
}
}
3、写一个持久化接口CustomerRepository 继承MongoRepository
package com.example.jdbc.jpa.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
//import org.springframework.data.repository.CrudRepository;
//import org.springframework.stereotype.Repository;
import com.example.jdbc.jpa.model.Customer;
public interface CustomerRepository extends MongoRepository<Customer, String> {
List<Customer> findByLastName(String lastName);
}
4、写一个测试类 注入CustomerRepository 和 MongoTemplate类
package com.example.jdbc.jpa.controler;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.jdbc.jpa.model.Customer;
import com.example.jdbc.jpa.repository.CustomerRepository;
@RestController
public class CustomerControler {
@Autowired //don't forget the setter
private CustomerRepository customerRepository;
@Autowired
private MongoTemplate mongoTemplate;
@Bean
@RequestMapping("/saveCustomer")
public String saveCustomer(){
Customer customer =new Customer("Jack", "Bauer");
customerRepository.save(customer);
System.out.println("44444");
return customer.toString();
}
@Bean
@RequestMapping("/getCustomer")
public String getCustomer(){
List<Customer> customers=customerRepository.findByLastName("Bauer");
System.out.println("44444");
Customer customer=customers.get(0);
return customer.toString();
}
@Bean
@RequestMapping("/getCustomerByTemplate")
public String getCustomerByTemplate(){
Query query = new Query();
query.addCriteria(Criteria.where("firstName").is("Jack1"));
List<Customer> customers = mongoTemplate.find(query, Customer.class);
return customers.get(0).toString();
}
}
5、在properties配置文件中添加mongodb连接
spring.data.mongodb.uri=mongodb://localhost:27017/test2
6、打印MongoDB日志
logging.level.org.springframework.data.mongodb.core= DEBUG