pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.yml 配置文件:
spring:
data:
mongodb:
uri: mongodb://localhost:27017/databaseName #无密码
新建Entity实体Inventory和SIze:(我用的是jdk14的record,或者可以直接手动生成构造器getter/setter)
public record Inventory(
String _id, String item, int qty, Size size, String status) {
}
public record Size(double h, double w, String uom) {
}
最后MongoDBTest.java:
Query通过传入Criteria实现复杂的查询操作(下列每个方法中的注释掉的代码),而BasicQuery通过传入json字符串就可以执行查询,Update和BasicUpdate同理。传入的json字符串和命令行操作mongo是几乎一样的。而Update/Query的方式更接近于SQL操作,更直观更好记。
@SpringBootTest
public class DbTest {
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void findAllInventories() {
List<Inventory> all = mongoTemplate.findAll(Inventory.class);
all.forEach(System.out::println);
}
@Test
public void insertOne() {
mongoTemplate.insert(
new Inventory("", "paper", 100, new Size(8.5, 11, "in"), "D")
);
}
@Test
public void insertMany() {
List<Inventory> list = Arrays.asList(
new Inventory("", "canvas", 100, new Size