【发布时间】:2025-12-17 15:30:01
【问题描述】:
当我调用模型映射器实体到 DTO 转换器方法时,我总是得到空指针异常。
这是将 dto 转换为实体的转换器服务,反之亦然
我以前没有处理过 DTO,这是我第一次使用 DTO,我还需要知道这是我实现 DTO 转换器服务的最佳方式还是有任何建议。
@Autowired
private ModelMapper modelMapper;
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
@Override
public NotificationDto entityToDtoNotification(Notification notification) {
ModelMapper mapper = new ModelMapper();
return mapper.map(notification, NotificationDto.class);
}
@Override
public Notification dtoToEntityNotification(NotificationDto notificationDto) {
ModelMapper mapper = new ModelMapper();
return mapper.map(notificationDto, Notification.class);
}
当我在测试调用中调用该方法时,我得到空值
class NotificationServiceImplTest {
@Autowired
private NotificationServiceImpl notificationService;
@MockBean
private NotificationRepository notificationRepository;
@Autowired
ConverterServiceImpl converterService;
@Test
public void testCreateTicket() {
Notification notification = new Notification();
notification.setId(1);
notification.setMessage("Hello Hashan");
NotificationDto notificationDto = new NotificationDto();
//I get the null value as return
notificationDto=converterService.entityToDtoNotification(notification);
Mockito.when(notificationRepository.save(notification)).thenReturn(notification);
assertThat(notificationService.save(notificationDto)).isEqualTo(notification);
converterService.entityToDtoNotification(notification);
}
}
通知实体
@Entity
@Table(name = "notification")
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Notification() {
}
public Notification(int id, String message) {
this.id = id;
this.message = message;
}
}
通知 DTO
public class NotificationDto {
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public NotificationDto(int id, String message) {
this.id = id;
this.message = message;
}
public NotificationDto() {
}
}
【问题讨论】:
-
能否请您包含 NotificationDto 和 Notification 类的代码?
标签: java spring-boot dto