【问题标题】:How to update only a subset of fields and update the repository?如何仅更新字段的子集并更新存储库?
【发布时间】:2023-04-07 21:28:01
【问题描述】:

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

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> {

【问题讨论】:

  • 你在使用spring-dataJpaRepository吗?如果不是,则分享ErrorCaseDataRepository.save()的实现
  • 您似乎也没有遵循 Java 代码约定(特别是变量命名),这使得这很难遵循。
  • 您是否在静态使用您的存储库?它应该是一个连接到服务中的 bean
  • 是的,repo 已自动装配到服务中。我已经编辑显示 impl
  • 你能告诉我 existingCaseData.getId() 的值(或者你的实体 ID 的 getter 方法是什么)吗?

标签: java hibernate spring-boot jpa postman


【解决方案1】:

您正在获取数据并将其传递到existingCaseData 并保存uiOutboundErrorCaseData。所以我的猜测是 Hibernate 正在向数据库中添加一个具有新 ID 和更新值的新对象。这当然取决于您的模型定义。特别是id

如果您在 Hibernate Session 中已经有一个与该 ID 关联的对象,我还认为 Hibernate 不会让您使用相同的 ID 保存 uiOutboundErrorCaseData。那么,为什么不使用新值更新existingCaseData 并将其保存回来。

【讨论】:

    【解决方案2】:

    我创建了一个可行的解决方案,虽然我意识到它可以改进,但它确实有效。唯一的缺点是我需要指定所有可以更新的字段,理想情况下我想要一个包含 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);
    

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-05
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多