ModelMapper not ignoring null values

≡放荡痞女 提交于 2019-12-25 01:15:35

问题


I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.

I have tried this but no luck:

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        modelMapper.createTypeMap(String.class, Date.class);
        modelMapper.addConverter(new StringToDate());
        modelMapper.addConverter(new DateToString());
        return modelMapper;
    }

Then I update my object like this:

    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        userDocument = this.modelMapper.map(user, UserDocument.class);
        this.usersRepository.save(userDocument);
    }

The user object has 1 property set at null while the object userDocument has it with a value, then when I save it in the database that value is gone (because it has transformed into null).

What can be wrong?

Thanks.


回答1:


Okay so that configuration isn't for the purpose I thought it was.

I've solved the issue by merging the updated object with the old one like this:

    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        this.modelMapper.map(user, userDocument);
        this.usersRepository.save(userDocument);
    }



回答2:


Mybatis framework? You have not set selective save --selective

<insert id="insertSelective" parameterType="com.zjl.domain"> insert into table_name <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="createDate != null"> create_date, </if> <if test="modifiedDate != null"> modified_date, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=BIGINT}, </if> <if test="createDate != null"> #{createDate,jdbcType=TIMESTAMP}, </if> <if test="modifiedDate != null"> #{modifiedDate,jdbcType=TIMESTAMP}, </if> </trim> </insert>



来源:https://stackoverflow.com/questions/56359427/modelmapper-not-ignoring-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!