SpringBoot接入mongodb例子,并有增删改查功能

1,首先,在pom.xml中添加依赖:

XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
	<!--上面这个依赖包含了Spring Data MongoDB的所有必要组件,
	下面是Springboot的start-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2,在 application.properties 或 application.yml 中配置MongoDB连接:

java 复制代码
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/my_database

3,然后,例如创建一个实体类User:

java 复制代码
该实体类是映射MongoDB集合中的文档。
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
 
@Document
public class User {
    @Id
    private String id;
    private String name;
	private String deptName;
    private int age;
	private int salary;
 
	private int pageNum;
	private int pageSize;
	
    // 省略构造器、getter和setter方法
}

4,创建一个UserRepository接口:

java 复制代码
使用Spring Data MongoDB提供的Repository接口来操作MongoDB,
这个接口继承自MongoRepository,它提供了基本的CRUD操作;
import org.springframework.data.mongodb.repository.MongoRepository;
 
public interface UserRepository extends MongoRepository<User, String> {

    // 这里MongoRepository提供了基本的CRUD方法,也可以自定义查询方法
	
}

5,创建一个UserService服务类:

java 复制代码
该服务类来调用Repository接口,
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
import java.util.Optional;
 
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
	
	@Autowired
    private MongoTemplate mongoTemplate;
	
	// 新增
    public User saveUser(User user) {
		// 单个新增
		mongoTemplate.save(user);
        
		// 批量插入
		// List<User> users = new ArrayList<>();
		// users.add(...);
		// mongoTemplate.save(users, User.class);
    }
 
	// 精确查询
    public Optional<User> getUserById(String id) {
        return mongoTemplate.findById(id);
    }
	
	// 模糊查询
	public Optional<User> getUserByCondition(String name) {
		String param = (null == name) ? "" : name.trim();
		Criteria criteria = Criteria.where("name").regex(".*" + param + ".*");
		/** 上面正则匹配包含param的情况,
		下面是匹配以param为开头的情况*/
		//Criteria criteria = Criteria.where("name").regex("^" + param);
		Query query = new Query(criteria);
		List<User> result = mongoTemplate.find(query, User.class);		
        return result;
    }

	// 模糊分页并排序查询
	public Optional<User> getUserByCondition(User user) {
		// 创建各种查询条件
		Criteria criteria = new Criteria()
		.andOperator(
			Criteria.where("age").gte(40),
			Criteria.where("salary").gt(500)
		).orOperator(
			Criteria.where("name").regex("a"),
			Criteria.where("name").regex("b")
		);
		
		// 创建查询对象
		Query query = new Query(criteria);
		
		// 并指定排序方式
		query.with(
			Sort.by(
				Sort.Order.desc("age"),
				Sort.Order.asc("name")
			)
		)
		// 分页处理
		.skip(pageNum*pageSize).limit(pageSize);			
		List<User> result = mongoTemplate.find(query, User.class);		
        return result;
    }
	 
	// 全部查询
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
	
	// 精确更新操作
	public void update(User user) {
		if (null == user) {
			return;
		}
		Criteria criteria = Criteria.where("id").is(user.getId());
		Query query = new Query(criteria);
		Update updateObj = new Update().set("age", user.getAge());
		mongoTemplate.updateFirst(query, updateObj, User.class);
	}
	
	// 批量更新操作
	public void update(User user) {
		if (null == user) {
			return;
		}
		Criteria criteria = Criteria.where("salary").gt(300);
		Query query = new Query(criteria);
		Update updateObj = new Update()
			.set("salary", 600)
			.set("deptName", "工程部");
		// 仅更新第一条
		mongoTemplate.updateFirst(query, updateObj, User.class);
		
		// 全部更新
		mongoTemplate.updateMulti(query, updateObj, User.class);
	}
	
	// 删除
    public void deleteUserById(String id) {
        Criteria criteria = Criteria.where("id").is(id);  
        Query query = new Query(criteria);
        mongoTemplate.remove(query,User.class);

    }
}

6,再创建一个UserController控制器类来处理HTTP请求:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
import java.util.Optional;
 
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
 
    @PostMapping
    public User addUser(@RequestBody User user) {
        return userService.saveUser(user);
    }
 
    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }
 
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
 
    @DeleteMapping("/{id}")
    public void deleteUserById(@PathVariable("id") String id) {
        userService.deleteUserById(id);
    }
}

7,创建一个启动类SpringBootDemoApplication:

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

一个简单例子,欢迎拍砖讨论...

相关推荐
鳄鱼杆9 分钟前
服务器 | Centos 9 系统中,如何部署SpringBoot后端项目?
服务器·spring boot·centos
千|寻15 分钟前
【画江湖】langchain4j - Java1.8下spring boot集成ollama调用本地大模型之问道系列(第一问)
java·spring boot·后端·langchain
程序员岳焱29 分钟前
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
后端·sql·mysql
龚思凯35 分钟前
Node.js 模块导入语法变革全解析
后端·node.js
天行健的回响37 分钟前
枚举在实际开发中的使用小Tips
后端
wuhunyu43 分钟前
基于 langchain4j 的简易 RAG
后端
techzhi43 分钟前
SeaweedFS S3 Spring Boot Starter
java·spring boot·后端
酷爱码1 小时前
Spring Boot 整合 Apache Flink 的详细过程
spring boot·flink·apache
cacyiol_Z1 小时前
在SpringBoot中使用AWS SDK实现邮箱验证码服务
java·spring boot·spring
写bug写bug2 小时前
手把手教你使用JConsole
java·后端·程序员