spring-boot - RestfulController POST(save)方法中动态字段的映射

标签 spring-boot grails groovy grails-orm gorm-mongodb

如何启用 RestfulController 自动映射甚至手动将动态字段映射到实现 MongoEntity 的域类?我有一个域类如下:

class Company implements MongoEntity<Company> {
    String id = UUID.randomUUID().toString()
    String name
    String email
    String phone
}

我有一个用于 CRUD 操作的 RestfulController 设置,如下所示
class CompanyController extends RestfulController<Company> {

@Transactional
    def save(Company company) {
        if(company.hasErrors()) {
            respond company.errors
        }
        else {
            company.insert(flush:true)
            respond company, status: CREATED
        }
    }
}

当我发布带有一些额外 JSON 字段的请求时,如何让它们自动映射到 gorm_dynamic_attributes ?目前,公司对象不返回有关动态属性的任何信息。我面临的另一个问题是 request.JSON也是空的,所以我也不能手动映射。任何建议将不胜感激。

最佳答案

我很确定,问题不在于 Controller 的数据绑定(bind),而在于域类实例的持久化。

我会像这样更改域类:

import grails.gorm.annotation.Entity

@Entity
class Company {
    String id
    String name
    String email
    String phone

    def beforeValidate() {
      if( !id ) setId UUID.randomUUID().toString()
    }  

    static mapping = {
      id generator:'assigned'
    }
}

使用 assigned发电机。您可以将您的 id 生成放在 Controller /服务代码中,或者将其留在域类中'beforeValidate .在后一种情况下,要特别注意何时生成 id,如 beforeValidate()经常被称为。另请注意,beforeValidate() 内部必须调用 setter。

我用 save() 测试了我的类似域类和 insert()在这两种情况下都像魅力一样。

关于spring-boot - RestfulController POST(save)方法中动态字段的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55833786/

相关文章:

Jenkins Groovy - 使用 readYaml 中的修改数据写回 yml 文件

mysql - Flyway 无法从 Docker-Container 连接到 MySQL

grails - XML 请求中与多个域类的数据绑定(bind)

testing - 在集成测试期间登录 Grails

grails - 如何在 grails codenarc 插件中包含自定义规则

unit-testing - 无法在Grails中模拟Thrift类进行测试(GroovyCastException)

java - 在使用 Hibernate 更新行时,在 Spring Boot 中收到错误 "detached entity passed to persist"

Java 可选的 getter 在模型映射器中不起作用

java - 如何为函数中的带注释参数编写mockito

validation - Grails中的电子邮件验证