java Map具有包含外键的属性的类时出错

anauzrmj  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(120)

我有Hardware实体、HardwareDtoRequestHardwareDtoResponse类,我使用modelMapperMap它们。在Hardware表中,有一个指向Provider表的外键。问题是我无法将此属性Map到HardwareDtoRequest。当我在Postman中调用POST方法时,只在请求体中传递provider_id,它只保存一个具有该特定ID的记录,当试图再次保存另一个具有相同ID的记录时,它会更新旧的记录。2如何将此外键属性Map到DtoRequest并保存?

硬件.java

@Getter
@Setter
@Entity
public class Hardware {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 100)
private String name;

@ManyToOne
@JoinColumn(name = "provider_id")
private Provider provider;

}

提供程序.java

@Getter
@Setter
@Entity
public class Provider {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, length = 100)
private String name;

}

硬件数据到请求.java

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class HardwareDtoRequest {

@NotNull(message = "required field")
private String name;

@NotNull(message = "required field")
private Long providerId;

}

硬件数据到响应.java

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class HardwareDtoResponse {

private Long id;
private String name;
private ProviderDtoResponse provider;

}

硬件Map器.java

public HardwareDtoResponse toHardwareDtoResponse(Hardware hardware) {
        
    return mapper.map(hardware, HardwareDtoResponse.class);
}
    
public Hardware toHardware(HardwareDtoRequest hardwareDtoRequest) {
        
    return mapper.map(hardwareDtoRequest, Hardware.class);
}

硬件服务.java

@Transactional
public HardwareDtoResponse save(HardwareDtoRequest hardwareDtoRequest) {
        
    Hardware hardware = mapper.toHardware(hardwareDtoRequest);
        
    Hardware saveHardware = hardwareRepository.save(hardware);

    return mapper.toHardwareDtoResponse(saveHardware);
}

硬件控制器.java

@PostMapping
public ResponseEntity<HardwareDtoResponse> save(@Valid @RequestBody HardwareDtoRequest hardwareDtoRequest) {
        
    log.info("saving hardware: {}", hardwareDtoRequest);    

    HardwareDtoResponse hardware = hardwareService.save(hardwareDtoRequest);
        
    return new ResponseEntity<>(hardware, HttpStatus.CREATED);
}
46qrfjad

46qrfjad1#

您可以尝试手动设置提供程序。如下所示:

public Hardware toHardware(HardwareDtoRequest hardwareDtoRequest) {
    Hardware hardware = mapper.map(hardwareDtoRequest, Hardware.class);
    Provider provider = providerRepository.findById(hardwareDtoRequest.providerId);
    hardware.setProvider(provider);
    return hardware;
}

相关问题