MongoDB教程(二)SpringBoot 集成 MongoDB 完成增删改查
1、创建SpringBoot工程
通过idea创建SpringBoot 工程,并添加一下pom依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mongodb</groupId>
<artifactId>spring-mongodb-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mongodb-example</name>
<description>spring-mongodb-example</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、在工程配置文件中,增加mongodb地址信息,这里使用的是mongodb的云服务Atlas.
# 登录用户所在的数据库
# 数据库的url地址
spring.data.mongodb.uri=mongodb+srv://julywhj:<password>@cluster0.r1o1v.mongodb.net/test
这里的地址可以直接通过云平台获取,可以参考(1条消息) MongoDB教程(一):MongoDB云服务免费开通_July_whj的博客-CSDN博客中信息查看。
3、编写Controller测试类
/**
* @author JulyWhj
*/
@RestController
@RequestMapping("/mongodbExample")
public class MongodbExampleController {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 查询全部 CollectionNames 名称
*
* @return
*/
@GetMapping("/getCollectionNames")
public R getCollectionNames() {
return R.of(mongoTemplate.getCollectionNames());
}
/**
* 创建订单数据
*
* @param orderModel
* @return
*/
@PostMapping("/createOrder")
public R createOrder(@RequestBody OrderModel orderModel) {
OrderModel order = mongoTemplate.save(orderModel, "order");
return R.of(order);
}
/**
* 更新订单数据
*
* @param orderModel
* @return
*/
@PostMapping("/updateOrder")
public R updateOrder(@RequestBody OrderModel orderModel) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(orderModel.getId()));
Update update = new Update();
update.set("materialName", orderModel.getMaterialName());
UpdateResult order = mongoTemplate.upsert(query, update, OrderModel.class, "order");
return R.of(order);
}
/**
* 根据ID查询数据
*
* @param id id
* @return
*/
@GetMapping("/findById")
public R findById(BigInteger id) {
OrderModel order = mongoTemplate.findById(id, OrderModel.class, "order");
return R.of(order);
}
/**
* 根据ID删除数据
*
* @param id id
* @return
*/
@DeleteMapping
public R deleteById(BigInteger id) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
DeleteResult order = mongoTemplate.remove(query, "order");
return R.of(order);
}
}
这里引用了订单的Model信息,
@Data
public class OrderModel implements Serializable {
@Id
private BigInteger id;
/**
* 销售订单编号
*/
private String orderNo;
/**
*
*/
private Integer orderStatus;
private Long saleUserId;
/**
* 收货方企业id
*/
private Long recipientId;
/**
* 订单来源,字典值:1官网 2 第三方导入 3 系统对接
*/
private String orderSource;
/**
* 供应商企业id(乙方)
*/
private Long supplierId;
/**
* 金额
*/
private BigDecimal amount;
/**
* 税额
*/
private Double taxAmount;
/**
* 订单扩展字段
*/
private JSONObject saleOrderExpandJson;
/**
* 物料编号
*/
private String materialId;
/**
* 物料名称
*/
private String materialName;
/**
* 销售数量
*/
private String saleNumber;
/**
* 计价单位
*/
private String priceUnit;
/**
* 计价数量
*/
private BigDecimal priceUnitQty;
/**
* 单价
*/
private BigDecimal price;
/**
* 含税单价
*/
private BigDecimal taxPrice;
/**
* 是否赠品
*/
private String isFree;
/**
* 金额
*/
private BigDecimal billAmount;
/**
* 小计
*/
private Double subtotal;
/**
* 到货时间
*/
private Date arrivalTime;
/**
* 物料扩展字段
*/
private JSONObject expandJson;
}
返回对象R
@Data
public class R {
private int code;
private String msg;
private Object data;
public static R of(Object data) {
R r = new R();
r.code = 200;
r.msg = "操作成功";
r.data = data;
return r;
}
}
至此,我们需要测试的编码已经完成,我们提前准备了一条数据,数据结构如下:
{
"id": 2460,
"orderNo": "XSDD-20220329-0044",
"saleOrderExpandJson": {
"isManufactureOrder": true,
"grossProfitMargin": 27,
"storageQuantity": 2650,
"estimatedCosts": 73.4,
"recipientAddress": "江苏省盐城东台测试地址1",
"waitingDeliveryQuantity": 100,
"spec": "500*400*300",
"orderQuantity": 100
},
"materialId": "48",
"materialName": "阀门包装3.0",
"isFree": "否",
"arrivalTime": "2022-03-28T16:00:00.000+00:00",
"expandJson": {
"isManufactureOrder": true,
"grossProfitMargin": 27,
"storageQuantity": 2650,
"estimatedCosts": 73.4,
"recipientAddress": "江苏省盐城东台测试地址1",
"waitingDeliveryQuantity": 100,
"spec": "500*400*300",
"orderQuantity": 100
}
}
启动服务,进行简单测试:
首先我们看下testdb中存在的Collection;
我们登陆客户端工具验证下:
OK,我们进行创建数据:
我们看到开始order中没有数据存在,我们调用create接口,插入数据:
可以看到数据插入成功了,我们在通过客户端验证下
更新数据:
数据更新成功,根据ID查询这里不过多说明。
删除数据:
我们根据ID将刚刚插入的数据已经删除,看到执行了1条数据的删除。
SpringBoot 整合 MongoDB进行简单的增删改查操作是非常简单的,后续为大家持续更新MongoDB更多高级的查询和原理。
更多内容请求关注微信公众号:杰子学编程