Spirngboot+Spring Data mongodb(三) 修改操作

新增数据

@Test
public void add(){
    List<BillDetail> details = new ArrayList<>();
    IntStream.range(0,3).parallel().forEach(x->{
        BillDetail billDetail = new BillDetail();
        String suffix = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSSS"));
        billDetail.setBillNo("0304"+ suffix);
        billDetail.setCity("深圳市"+x);
        billDetail.setProvince("广东省"+x);
        billDetail.setCounty("福田区"+x);
        billDetail.setPrice(100+x);
        billDetail.setSex("男");
        billDetail.setUsername("王小二"+x);
        billDetail.setSpuName(Arrays.asList("品类"+ new Random().nextInt(100),"品类"+new Random().nextInt(100)));
        List<ProductInfo> productInfos = new ArrayList<>();
        IntStream.range(0,3).parallel().forEach(p->{
            ProductInfo productInfo = new ProductInfo();
            productInfo.setPrice(300+p);
            productInfo.setName("可口可乐"+p);
            productInfo.setType("汽水"+p);
            productInfos.add(productInfo);
        });
        billDetail.setProductInfos(productInfos);
        details.add(billDetail);
    });
    mongoTemplate.insertAll(details);
}

updateFirst更新 匹配county为福田的 第一条数据的city为 深圳

 @Test
    public void update1(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = Update.update("city", "深圳市");
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

updateMulti更新所有匹配结果

 @Test
    public void update2(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = Update.update("city", "深圳市");
        mongoTemplate.updateMulti(query,update,BillDetail.class);
    }

upsert 单条操作,若query条件匹配,这执行更新匹配的第一条,若无则新增一条记录

public void update3(){
        Criteria city = Criteria.where("county").regex("宝安*");
        Query query = Query.query(city);
        Update update = Update.update("city", "深圳市");
        mongoTemplate.upsert(query,update,BillDetail.class);
    }

 addToSet 数组增加一条记录

 public void update4(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.addToSet("spu_name","品类add");
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

 addToSet数组新增多条数据

public void update5(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.addToSet("spu_name").each(Arrays.asList("品类add","品类add2","品类add3"));
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }
新增一个category 数组,当数组内存在相同数据时,addToSet不新增,push会直接新增
 public void update6(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.push("category").each("spring", "data");
//        update.addToSet("category").each("spring", "data");
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

currentDate时间操作

修改updateTime字段时间为当前时间,若updateTime字段不存在,则新增字段,mongodb时间对比北京时间会少8个小时。
 public void update7(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.currentDate("updateTime");
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

pop 数组集合的头部或尾部删除一个元素

    public void update8(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
//        update.pop("spu_name", Update.Position.LAST);
        update.pop("spu_name", Update.Position.FIRST);
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

pull删除集合元素

单条匹配,删除spu_name集合中所有 “品类add”
 public void update9(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.pull("spu_name","品类add");
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }
删除数组内  "品类add","品类add2","品类84"多种匹配记录
public void update10(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.pullAll("spu_name",new Object[]{"品类add","品类add2","品类84"});
        mongoTemplate.updateFirst(query,update,BillDetail.class);
    }

setOnInsert插入新增

 query条件有匹配文档,则不执行更新操作,query条件没有匹配文档,新增一条 Key-value(sex:女)的文档
 public void update11(){
        Criteria city = Criteria.where("county").regex("宝安*");
        Query query = Query.query(city);
        Update update = new Update();
        update.setOnInsert("sex","女");
        mongoTemplate.upsert(query,update,BillDetail.class);
    }

findAndModify 是否返回更新后的结果

    public void update13(){
        Criteria city = Criteria.where("county").regex("福田*");
        Query query = Query.query(city);
        Update update = new Update();
        update.inc("price",10);
        BillDetail andModify = mongoTemplate.findAndModify(query, update, FindAndModifyOptions.options().returnNew(true), BillDetail.class);
        System.out.println(andModify);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的基于Spring Boot、Thymeleaf和MongoDB的员工管理系统的实现: 1. 首先,需要引入相关依赖。在项目的pom.xml文件中添加以下依赖: ```xml <dependencies> <!-- Spring Boot web starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Spring Boot MongoDB starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> ``` 2. 创建Employee类表示员工实体,包括姓名、年龄、职位等属性,以及相应的getter和setter方法。例如: ```java public class Employee { private String id; private String name; private int age; private String position; // getter and setter methods } ``` 3. 创建EmployeeRepository接口继承MongoRepository,用于操作MongoDB数据库中的Employee集合。例如: ```java public interface EmployeeRepository extends MongoRepository<Employee, String> { // 根据名称查询员工 List<Employee> findByName(String name); // 根据职位查询员工 List<Employee> findByPosition(String position); } ``` 4. 创建EmployeeController类作为员工管理系统的控制器,处理员工信息的增删改查等操作。例如: ```java @Controller public class EmployeeController { @Autowired private EmployeeRepository repository; // 查询所有员工 @GetMapping("/") public String index(Model model) { List<Employee> employees = repository.findAll(); model.addAttribute("employees", employees); return "index"; } // 新增员工 @GetMapping("/add") public String add(Model model) { model.addAttribute("employee", new Employee()); return "add"; } @PostMapping("/add") public String add(Employee employee) { repository.save(employee); return "redirect:/"; } // 修改员工信息 @GetMapping("/edit/{id}") public String edit(@PathVariable String id, Model model) { Employee employee = repository.findById(id).orElse(null); model.addAttribute("employee", employee); return "edit"; } @PostMapping("/edit") public String edit(Employee employee) { repository.save(employee); return "redirect:/"; } // 删除员工 @GetMapping("/delete/{id}") public String delete(@PathVariable String id) { repository.deleteById(id); return "redirect:/"; } // 查询员工 @PostMapping("/search") public String search(String keyword, Model model) { List<Employee> employees = repository.findByNameOrPosition(keyword, keyword); model.addAttribute("employees", employees); return "index"; } } ``` 5. 创建Thymeleaf模板,实现员工信息的展示、新增、修改和删除等操作。例如: index.html ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Employee Management System</title> </head> <body> <h1>Employee Management System</h1> <p><a th:href="@{/add}">Add Employee</a></p> <form th:action="@{/search}" method="post"> <input type="text" name="keyword" placeholder="Search by Name or Position"/> <button type="submit">Search</button> </form> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Position</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each="employee : ${employees}"> <td th:text="${employee.id}"></td> <td th:text="${employee.name}"></td> <td th:text="${employee.age}"></td> <td th:text="${employee.position}"></td> <td> <a th:href="@{/edit/{id}(id=${employee.id})}">Edit</a> <a th:href="@{/delete/{id}(id=${employee.id})}">Delete</a> </td> </tr> </tbody> </table> </body> </html> ``` add.html ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Add Employee</title> </head> <body> <h1>Add Employee</h1> <form th:action="@{/add}" method="post"> <div> <label>Name:</label> <input type="text" name="name"/> </div> <div> <label>Age:</label> <input type="number" name="age"/> </div> <div> <label>Position:</label> <input type="text" name="position"/> </div> <button type="submit">Save</button> </form> </body> </html> ``` edit.html ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Edit Employee</title> </head> <body> <h1>Edit Employee</h1> <form th:action="@{/edit}" method="post"> <input type="hidden" name="id" th:value="${employee.id}"/> <div> <label>Name:</label> <input type="text" name="name" th:value="${employee.name}"/> </div> <div> <label>Age:</label> <input type="number" name="age" th:value="${employee.age}"/> </div> <div> <label>Position:</label> <input type="text" name="position" th:value="${employee.position}"/> </div> <button type="submit">Save</button> </form> </body> </html> ``` 6. 最后,配置MongoDB数据库连接。在application.properties文件中添加以下配置: ```properties spring.data.mongodb.uri=mongodb://localhost:27017/employee ``` 其中,employee为MongoDB数据库名称。 至此,一个基于Spring Boot、Thymeleaf和MongoDB的员工管理系统就完成了。可以使用浏览器访问http://localhost:8080/来体验该系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值