MongoDB简介
MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下,添加更多的节点,可以保证服务器性能。
MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
引入mongoDB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
MongoDB数据源配置
无设置账户密码配置
spring.data.mongodb.uri=mongodb://localhost:27017/dbname
设置账户密码时配置
spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbname #name账户名/pass密码
定义实体类
package com.forezp.entity;
import org.springframework.data.annotation.Id;
public class Customer {
@Id
public String id; // 文档的唯一标识,在mongodb中为ObjectId,它是唯一的
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);
}
}
DAO层:类似jpa继承MongoRepository
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已经帮你实现了。
@SpringBootApplication
public class SpringbootMongodbApplication implements CommandLineRunner {
@Autowired
private CustomerRepository repository;
// 除了使用CustomerRepository,也可以通过mongoTemplate原生接口查询
// @Autowired
// private MongoTemplate mongoTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringbootMongodbApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
repository.deleteAll();
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
System.out.println("Customers found with findAll():");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
转载:https://www.toutiao.com/i6647693472696369678/