简体   繁体   English

类似于Spring中的Grails域属性字段吗?

[英]Something similar to Grails Domain properties field in Spring?

I have started a new project in Spring Boot after using Grails for 4 years. 使用Grails四年后,我在Spring Boot中启动了一个新项目。 In Grails I have used properties field of an instance of a domain class to update the associate row in a db table. 在Grails中,我使用了域类实例的properties字段来更新db表中的关联行。 The assignment of domain.properties was usually done inside a service. domain.properties的分配通常在服务内部完成。 The properties field was set with data coming from a web form. properties字段设置为来自Web表单的数据。 This approach allows to update a domain instance with a single line, instead of writing n assignemnt, where n is the number of the attributes defined in the domain class. 这种方法允许用一行来更新域实例,而不用编写n个被分配的对象,其中n是域类中定义的属性的数量。

Now the question.. there is something similar in Spring? 现在的问题..春天有类似的事情吗? I would like to do something similar in Spring: 我想在春季做类似的事情:

update(Long radioId,Map properties) {
      // get the radio to be update from the db
      Radio radio = getRadio(radioId) 
      radio.properties = properties 
      save(radio)
}

I add some detail, My controller 我添加一些细节,我的控制器

public ModelAndView updateRadio(Radio radio) {
        radioService.update(radio);
        return new ModelAndView("redirect:/superadmin/radio/"+radio.getIdentifier()+"/zoom");
    }

My Service 我的服务

@Service
public class RadioService {
...

    public void update(Radio radio) {
            assert radio.getId() != null;
            radioRepository.save(radio);
    }
...
}

Now if the web form does not explicity send all the fields defined in Radio I have problem since I will loose the value of the field already stored. 现在,如果Web表单未明确发送Radio中定义的所有字段,则我将遇到问题,因为我将丢失已经存储的字段的值。 If I could write somthing like that 如果我能写这样的东西

public void update(Map radioProperties,Long radioId) {
  Radio radio = radioRepository.findById(radioId);
  radio.properties = radioProperties // only properties present in this map will be update (in grails)
  radioRepository.save(radio);
}

it would be great. 这会很棒。
In the latter method only the properties in the map (ence in the web form) will be updated, and the other store field of the radio instance will be untouched. 在后一种方法中,仅地图中的属性(Web表单中的出现)将被更新,单选实例的其他商店字段将保持不变。

看一下Spring Data JPA ,它可以按ID加载域对象,将传入的请求参数绑定到域对象,还可以自动创建一些CRUD存储库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM