如何仅更新字段的一部分并更新存储库?

编码器

我正在制作一个Spring Boot应用程序,并且希望通过我的服务和控制器更新数据库中的现有条目。在我的服务层中,我有以下方法。因此,我要检索与caseID关联的字段,创建一个模型映射器,将我的实体对象类映射到我的VO,然后将检索到的数据映射到我的DTO。然后,我保存我的存储库。目的是仅添加我在请求消息中指定的字段,即,如果我只想更新20个字段中的1个,它将更新此字段,其余部分保持不变。以下代码可以成功运行,但是我在邮递员的请求消息中指定的字段不会在数据库中更新。为什么是这样?我尝试映射不同的对象并将不同的变量保存到存储库,但是似乎没有任何更新DB。

public StoredOutboundErrorCaseVO updateCase(OutboundErrorCaseVO outboundErrorCaseVO, Long caseNumber) {
    OutboundErrorCaseData existingCaseData = ErrorCaseDataRepository.findById(caseNumber).get();
    ModelMapper mm = new ModelMapper();
    mm.getConfiguration().setAmbiguityIgnored(true);
    OutboundErrorCaseData uiOutboundErrorCaseData = mm.map(outboundErrorCaseVO,
            OutboundErrorCaseData.class);
    mm.map(existingCaseData, uiOutboundErrorCaseData);
    ErrorCaseDataRepository.save(uiOutboundErrorCaseData);
    return mm.map(uiOutboundErrorCaseData, StoredOutboundErrorCaseVO.class);
}

控制器-为简洁起见,省略了POST方法的代码(我通常使用PUT进行更新,但我相信我仍然可以使用POST)

    StoredOutboundErrorCaseVO updatedCase = outboundErrorService.updateCase(outboundErrorCaseVO,
            caseNumber);

回购

    @Repository
public interface OutboundErrorCaseDataRepository extends JpaRepository<OutboundErrorCaseData, Long> {
编码器

我创建了一个可行的解决方案,尽管我知道它可以改进,但肯定可以。唯一的缺点是,我需要指定所有可以更新的字段,理想情况下,我想要一个采用n个字段并更新记录的解决方案。

OutboundErrorCaseData existingCaseDta = ErrorCaseDataRepository.findById(caseNumber).get();
    if (outboundErrorCaseVO.getChannel() != null) {
        existingCaseDta.setChannel(outboundErrorCaseVO.getChannel());
    }
ErrorCaseDataRepository.save(existingCaseDta);
    ModelMapper mm = new ModelMapper();
    return mm.map(existingCaseDta, StoredOutboundErrorCaseVO.class);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章