首页 > 解决方案 > 保存休眠对象而不获取外键实体,仅按 id 保存

问题描述

我正在将带有 Hibernate 的对象“产品”保存到数据库中。Product 对象具有不作为 id 的依赖对象。在数据库中,它被保存为外键。下面的代码是获取保存对象 Product 的依赖对象的一部分。所以每次保存产品时,我们都会对数据库进行不必要的调用,因为我们已经知道依赖对象的 id。我怎样才能以更好的方式做到这一点?

        Rubric rubric = rubricRepository.findById(productRequestDto.getRubricId())
            .orElseThrow(() -> new EntityNotFoundException(productRequestDto.getRubricId().toString()));
    User user = userRepository.findById(productRequestDto.getUserId())
            .orElseThrow(() -> new EntityNotFoundException(productRequestDto.getUserId().toString()));
    Condition condition = conditionRepository.findById(productRequestDto.getConditionId())
            .orElseThrow(() -> new EntityNotFoundException(productRequestDto.getConditionId().toString()));
    Color color = colorRepository.findById(productRequestDto.getColorId())
            .orElseThrow(() -> new EntityNotFoundException(productRequestDto.getColorId().toString()));

标签: databasehibernatejpa

解决方案


推荐阅读