The Spring MVC binding mechanism is powerful, but I’m now confronted with a trivial issue that I wonder how to resolve:
UserJPA entity, that is used for the binding and validation as well (i.e. throughout all layers)- “Edit profile” page, that is not supposed to change the password or some other entity properties
Two ways that I can think of:
-
Using the same object
- use
@InitBinderto configure a list of disallowed properties - obtain the target user (by id)
- then use a reflection utility (BeanUtils) to copy the submitted object to the target object, but ignore
nullvalues – i.e. fields that are not submitted
- use
-
Introduce a new object that has the needed subset of fields, and use
BeanUtils.copyProperties(..)to merge it to the entity.
Alternatives?
I’ve found that as soon as your web model starts to diverge from your business layer in function, it’s best to use a view layer object (a model object) to collect, or display the data
the entity:
the model object:
now all view based operations can hand off processing to the internal model object if that makes sense, otherwise it can customize them itself. Of course the problem with this is you have to re-write all the getters and setters you want for the entity (an issue that I’ve had to deal with, that is annoying) unfortunately that is a bit of a Java language issue