1、添加MongoDB依赖,版本号根据springboot来,一把都会有默认的
<!-- Spring Data MongoDB -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、配置连接信息
spring.data.mongodb.uri=mongodb://localhost:27017/your_database_name
3、创建实体类
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private double price;
private String description;
// 构造函数、Getter和Setter等省略...
}
4、继承 MongoRepository 接口
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ProductRepository extends MongoRepository<Product, String> {
List<Product> findByName(String name);
}
5、示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
// 创建或更新产品
public Product saveProduct(Product product) {
return productRepository.save(product);
}
// 根据ID查找产品
public Product findProductById(String id) {
return productRepository.findById(id).orElse(null);
}
// 根据name查找产品
public List<Product> findProductById(String name) {
return productRepository.findByName(name).orElse(null);
// return productRepository.findByNameAndId(name, id).orElse(null);
// return productRepository.findByNameAndPriceBetweenOrderByTsDesc(name, startPrice, endPrice)
}
// 获取所有产品
public List<Product> getAllProducts() {
return productRepository.findAll();
}
// 根据ID删除产品
public void deleteProductById(String id) {
productRepository.deleteById(id);
}
}
6、测试
public class Main {
public static void main(String[] args) {
// 假设已经有一个Spring应用程序,并且已经注入了ProductService
ProductService productService = ... // 注入ProductService
// 创建一个产品
Product product1 = new Product();
product1.setName("Product 1");
product1.setPrice(19.99);
product1.setDescription("This is product 1.");
Product savedProduct1 = productService.saveProduct(product1);
// 查询产品
Product foundProduct = productService.findProductById(savedProduct1.getId());
System.out.println("Found product: " + foundProduct);
// 获取所有产品
List<Product> allProducts = productService.getAllProducts();
System.out.println("All products: " + allProducts);
// 删除产品
productService.deleteProductById(savedProduct1.getId());
}
}