我来为你详细讲解“Java SpringBoot MongoDB增删改查代码实例”的完整攻略。
简介
SpringBoot是一个基于Spring Framework的全栈( Full-stack)框架,可以快速构建Web应用程序。它提供了一系列的依赖管理和编码规范,使得我们可以专注于业务逻辑而不是繁琐的配置。MongoDB是一种文档数据库,支持各种数据类型和查询方式。
本攻略旨在介绍如何使用Java SpringBoot框架和MongoDB进行增删改查。
环境搭建
在开始本攻略之前,我们需要进行一些准备工作。
- 安装 JDK 8 或以上版本。
- 安装 MongoDB 数据库服务,详见MongoDB官网。
- 安装 MongoDB可视化管理工具 MongoDB Compass。
- 新建Maven项目并导入MongoDB和SpringBoot相关依赖。
在项目的pom.xml文件中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.1.1</version>
</dependency>
实现增删改查
定义实体类
在开始实现增删改查之前,我们需要定义一个数据模型,即Java实体类。本文提供的示例代码中,我们定义一个名为Employee的实体类。
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "Employee")
public class Employee {
@Id
private String id;
private String firstName;
private String lastName;
private Long salary;
}
数据库连接
接下来我们需要建立与MongoDB的连接。在SpringBoot中,我们可以通过在application.properties文件中配置数据库连接信息来实现连接。
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test_database
增加文档
下面是向MongoDB中添加一个文档的示例代码:
@Autowired
private MongoTemplate mongoTemplate;
public Employee addEmployee(Employee employee) {
return mongoTemplate.save(employee);
}
查询文档
下面是从MongoDB中查询文档的示例代码:
@Autowired
private MongoTemplate mongoTemplate;
public List<Employee> findAllEmployees() {
return mongoTemplate.findAll(Employee.class);
}
public Employee findEmployeeById(String id) {
Query query = new Query(Criteria.where("id").is(id));
return mongoTemplate.findOne(query, Employee.class);
}
public List<Employee> findEmployeeByLastName(String lastName) {
Query query = new Query(Criteria.where("lastName").is(lastName));
return mongoTemplate.find(query, Employee.class);
}
更新文档
下面是更新MongoDB中的文档的示例代码:
@Autowired
private MongoTemplate mongoTemplate;
public long updateEmployee(Employee employee) {
Query query = new Query(Criteria.where("id").is(employee.getId()));
Update update = new Update();
update.set("firstName", employee.getFirstName());
update.set("lastName", employee.getLastName());
update.set("salary", employee.getSalary());
UpdateResult result = mongoTemplate.updateFirst(query, update, Employee.class);
if (result != null) {
return result.getModifiedCount();
} else {
return 0L;
}
}
删除文档
最后,我们需要删除MongoDB中的一个文档。下面是一个示例代码:
@Autowired
private MongoTemplate mongoTemplate;
public void deleteEmployeeById(String id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, Employee.class);
}
示例
下面是根据上述代码实现的两个示例。
示例1
在这个示例中,我们以RESTful API方式将一个员工进行添加、查询、更新和删除操作。
在EmployeeController.java中实现如下代码:
@RestController
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
// Get all employees
@GetMapping("/getAllEmployees")
public List<Employee> getAllEmployees() {
return employeeService.findAllEmployees();
}
// Get an employee by id
@GetMapping("/getEmployeeById/{id}")
public Employee getEmployeeById(@PathVariable String id) {
return employeeService.findEmployeeById(id);
}
// Get employees by lastName
@GetMapping("/getEmployeesByLastName/{lastName}")
public List<Employee> getEmployeesByLastName(@PathVariable String lastName) {
return employeeService.findEmployeeByLastName(lastName);
}
// Add an employee
@PostMapping("/addEmployee")
public Employee addEmployee(@RequestBody Employee employee) {
return employeeService.addEmployee(employee);
}
// Update an employee
@PutMapping("/updateEmployee")
public long updateEmployee(@RequestBody Employee employee) {
return employeeService.updateEmployee(employee);
}
// Delete an employee
@DeleteMapping("/deleteEmployeeById/{id}")
public void deleteEmployeeById(@PathVariable String id) {
employeeService.deleteEmployeeById(id);
}
}
示例2
在这个示例中,我们以MongoTemplate方式进行文档操作,实现将一个员工添加进MongoDB数据库、查询、更新和删除操作。示例代码如下:
@SpringBootApplication
public class MongoDemoApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(MongoDemoApplication.class, args);
EmployeeService employeeService = context.getBean(EmployeeService.class);
// 添加Employee
Employee employee = new Employee(null, "Jack", "Smith", 80000L);
Employee addedEmployee = employeeService.addEmployee(employee);
System.out.println("Added employee: " + addedEmployee);
// 根据ID查询Employee
String addedEmployeeId = addedEmployee.getId();
Employee foundEmployee = employeeService.findEmployeeById(addedEmployeeId);
System.out.println("Found employee by ID: " + foundEmployee);
// 根据lastName查询Employee
List<Employee> foundEmployeesByLastName = employeeService.findEmployeeByLastName("Smith");
System.out.println("Found employees by lastName: " + foundEmployeesByLastName);
// 更新Employee
Employee updatedEmployee = foundEmployee;
updatedEmployee.setSalary(90000L);
long updatedCount = employeeService.updateEmployee(updatedEmployee);
System.out.println("Updated employee count: " + updatedCount);
// 删除Employee
String updatedEmployeeId = updatedEmployee.getId();
employeeService.deleteEmployeeById(updatedEmployeeId);
System.out.println("Deleted employee by ID: " + updatedEmployeeId);
}
}
至此,我们已经实现了Java SpringBoot MongoDB的增删改查。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java springboot Mongodb增删改查代码实例 - Python技术站