Spring Boot和Kotlin中的部分更新REST
我有一个Spring Boot + Kotlin + Morphia项目。
我需要添加我的实体的部分更新。 我的实际发布方法:
@PostMapping("update/") fun updateStudent(@RequestBody @Valid student: Student, results: BindingResult): ResponseData<Student> { if (results.hasErrors()) return ResponseData(errors = results.errors) if (!student.canEdit(login.user)) return ResponseData() student.save() return ResponseData(data = student) }
我需要从数据库中读取学生,只更新发回的字段
有两件事要实施。 从数据库中读取学生并从请求中复制学生的属性。
我发布的Java代码,但没有问题,转换为kotlin
Morphia morphia = new Morphia(); db = new Mongo(); Datastore ds = morphia.createDatastore(db, appname, user, pass.toCharArray()); morphia.map(Student.class); Student existing= ds.find(Student.class).field("id").equal(student.id).get();
然后你可以使用Apache BeanUtils
BeanUtils.copyProperties(existing, student);
然后
existing.save();