Bootstrap

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

1,首先,在pom.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连接:

spring.data.mongodb.uri=mongodb://username:password@localhost:27017/my_database

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

该实体类是映射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接口:

使用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服务类: 

该服务类来调用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请求:

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:

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);
    }
}

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

;