1

I have bean with approximately 100 fields.

On jsp I have 20 fields which I can update.

I need to update only 20 fields when I submit form and retain all rest fields(80) without changes for concrete bean.

I know that I can read bean from database and write 20 setters and then update bean. Also it is ugly to write 20 request parameters as arguments of controller method

Does spring provide more elegant way to resolve my task?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • possible duplicate of [Spring MVC + Hibernate: Partial model update from browser](http://stackoverflow.com/questions/14006517/spring-mvc-hibernate-partial-model-update-from-browser) – Gergely Bacso Sep 05 '15 at 13:17
  • 1
    @Gergely Bacso Answers from your link doesn't look very nice for may situation – gstackoverflow Sep 05 '15 at 13:30
  • possible duplicate of [Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security](http://stackoverflow.com/questions/29039116/spring-mvc-validation-post-redirect-get-partial-updates-optimistic-concurren) – Neil McGuigan Sep 05 '15 at 21:19

2 Answers2

0

in the handler that supplies the view name for the form jsp you could initialize a new model bean. this would result in a bean having default values of all the bean's field. Or you could inject it from the application context where the values of the bean's field may have been set.

pass this bean as a model attribute to the jsp form view.

 bean = context.getBean("beanName") or bean = new Bean();    
 modelAndView.addObject("bean",bean);

now include this model object in the session using @SessionAttributes.

@SessionAttributes("bean")

as soon as your handler method finishes execution your bean would be written in the session scope with all the field values.

you could use the following form to update the 20 fields

<form:form action="handler's  requestMapping" modelattribute="bean">
<form:input path="bean's first property name" />
 <%-- other properties similarly -->
</form:form>

in the handler method catering to the form submission use @ModelAttribute to access the bean which was submitted as model attribute to the form.

@RequestMapping("XXXX")
public ModelAndView/String handlerMethod(@ModelAttribute("bean") Bean bean) { /* method code here */
}

as soon as this handler method is invoked on form's submission the spring will read your bean from the session scope and at the same time update only those 20 fields which you have updated in the form. This way only 20 of your fields were updated while the others are retained as it is.

Nish
  • 31
  • 1
  • 6
0

If I rightly understood, we are trying to copy only certain fields from one bean to another, having said that I would tend to use org.dozer.DozerBeanMapper, which would do the necessary work for us.

new DozerBeanMapper().map(sourceObj, targetObj);

https://howtodoinjava.com/automation/dozer-bean-mapping-examples/

Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57