使用模型映射器更新实体
我在模型映射器上有一个奇怪的问题。可能我错过了它是如何工作的。 我拥有的:一个示例模型类:
class Model{
String name;
String surname;
Integer age;
...and much much more
一个方法
private void foo(){
ModelMapper modelMapper = new ModelMapper();
Model model = Model.builder().name("foo").surname("bar").age(23).build();
Model newModel = Model.builder().name("john").build();
modelMapper.map(newModel, model);
System.out.println(model.toString());
}
和输出是:模型(name = john,surname = null,age = null)
但是我期望的模型(名称= John,姓氏= bar,age = 23)
我可以使用模型映射器执行此操作吗?如果没有,如何轻松执行此操作(我不想手动更新每个属性)?谢谢。
I have a strange problem with model mapper. Probably I missunderstand how it works.
What I have: an example Model class:
class Model{
String name;
String surname;
Integer age;
...and much much more
And a method
private void foo(){
ModelMapper modelMapper = new ModelMapper();
Model model = Model.builder().name("foo").surname("bar").age(23).build();
Model newModel = Model.builder().name("john").build();
modelMapper.map(newModel, model);
System.out.println(model.toString());
}
And the output is: Model(name=john, surname=null, age=null)
But what I expect Model(name=john, surname=bar, age=23)
Can I do this using model mapper? If not, how to do this easily (i dont want update manually each property)? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用Lombok Builder
@Builder.default
轻松执行此操作You can do it easily using Lombok builder
@Builder.Default
You just need to update your Model class是的,您误解了它的工作原理:在您的情况下它运行良好。它也正在映射空值。如果您不想要它,则可以在专用于ModelMapper的Spring配置类中使用该代码:
重要的部分是
setSkipnullabled(true)
在此处全球处理该代码。当您处理表格时,请考虑一下。Yes you misunderstood how it works : it works well in your case. It is mapping null values too. If you do not want that, you can use that code inside a Spring Configuration class dedicated to ModelMapper :
The important part is
setSkipNullEnabled(true)
which handle that globally here. Take care of that when you are handling forms.