BOOKJAVA Telegram 3877
🧠 Spring Boot + MapStruct: как избежать null при обновлении сущности

При обновлении сущностей через MapStruct бывает типичная проблема: маппер затирает уже существующие поля null'ами, если они не переданы во входном DTO. Это может легко привести к потере данных. Покажу, как решить это изящно.

Допустим, у нас есть:


public class UserDto {
private String name;
private String email;
}


И сущность:


@Entity
public class User {
private String name;
private String email;
}


Если ты используешь обычный @MappingTarget, то:


@MappingTarget User user, UserDto dto


— не переданное поле email в dto затирает значение в user.

📌 Чтобы этого не происходило, добавь в маппер:


@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserMapper {
void update(@MappingTarget User user, UserDto dto);
}


💡 NullValuePropertyMappingStrategy.IGNORE говорит MapStruct: не трогай те поля, которые в DTO пришли как null.

⚠️ Это работает только для объектов, не для Optional и не для примитивов. Там потребуется другая стратегия — например, обёртки или @Condition.

Такой подход позволяет обновлять только те поля, которые реально пришли, и не бояться случайного затирания.

👉@BookJava
👍54



tgoop.com/BookJava/3877
Create:
Last Update:

🧠 Spring Boot + MapStruct: как избежать null при обновлении сущности

При обновлении сущностей через MapStruct бывает типичная проблема: маппер затирает уже существующие поля null'ами, если они не переданы во входном DTO. Это может легко привести к потере данных. Покажу, как решить это изящно.

Допустим, у нас есть:


public class UserDto {
private String name;
private String email;
}


И сущность:


@Entity
public class User {
private String name;
private String email;
}


Если ты используешь обычный @MappingTarget, то:


@MappingTarget User user, UserDto dto


— не переданное поле email в dto затирает значение в user.

📌 Чтобы этого не происходило, добавь в маппер:


@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserMapper {
void update(@MappingTarget User user, UserDto dto);
}


💡 NullValuePropertyMappingStrategy.IGNORE говорит MapStruct: не трогай те поля, которые в DTO пришли как null.

⚠️ Это работает только для объектов, не для Optional и не для примитивов. Там потребуется другая стратегия — например, обёртки или @Condition.

Такой подход позволяет обновлять только те поля, которые реально пришли, и не бояться случайного затирания.

👉@BookJava

BY Библиотека Java разработчика




Share with your friend now:
tgoop.com/BookJava/3877

View MORE
Open in Telegram


Telegram News

Date: |

Private channels are only accessible to subscribers and don’t appear in public searches. To join a private channel, you need to receive a link from the owner (administrator). A private channel is an excellent solution for companies and teams. You can also use this type of channel to write down personal notes, reflections, etc. By the way, you can make your private channel public at any moment. Step-by-step tutorial on desktop: Telegram is a leading cloud-based instant messages platform. It became popular in recent years for its privacy, speed, voice and video quality, and other unmatched features over its main competitor Whatsapp. Members can post their voice notes of themselves screaming. Interestingly, the group doesn’t allow to post anything else which might lead to an instant ban. As of now, there are more than 330 members in the group. During the meeting with TSE Minister Edson Fachin, Perekopsky also mentioned the TSE channel on the platform as one of the firm's key success stories. Launched as part of the company's commitments to tackle the spread of fake news in Brazil, the verified channel has attracted more than 184,000 members in less than a month.
from us


Telegram Библиотека Java разработчика
FROM American