代码之家  ›  专栏  ›  技术社区  ›  Vojtech

如何从列表中删除一个实体并添加一个新实体而不违反唯一约束?

  •  0
  • Vojtech  · 技术社区  · 6 年前

    @Entity
    public class Calculation {
        @Id
        @GeneratedValue(strategy = IDENTITY)
        private Long id;
    
        @OneToMany(fetch = LAZY, cascade = ALL, orphanRemoval = true)
        @JoinColumn(name = "calculation_id", referencedColumnName = "id", nullable = false, foreignKey = @ForeignKey(name = "fk_standard_part"))
        private List<Part> parts;
    }
    
    @Entity
    public class Part {
        @Column
        private String position;
    
        @Column
        private String positionDetail;
    }
    

    我正在使用Hibernate和Spring数据:

    1. 我从数据库中提取计算结果,然后填充零件列表。
    2. 我用position='SIDE',position\u detail='WINDOW'创建新零件,并将其添加到列表中。
    3. 我使用crudepository.save()保存计算

    请告知我做错了什么。如果可能,我不想更新零件实体。它有许多其他属性可能需要清除,因此我更喜欢替换它。非常感谢。

    编辑1: 代码如下:

    public Part repairStandardPart(Long calcId, String partNumber) {
        Part part = fetchNewPart(partNumber);
        Calculation calculation = getCalculation(calcId);
        // If there's a part with the same position allready I want to remove it...
        deletePartsAtPosition(calculation.getParts(), part.getPosition(), part.getSidePosition());
        // ...and then add the new one.
        calculation.getParts().add(part);
        calculationRepository.save(calculation);
        return part;
    }
    
    private void deletePartsAtPosition(List<Part> parts, String position, String positionDetail) {
        parts.removeIf(p -> Objects.equals(p.getPosition(), position) && Objects.equals(p.getPositionDetail(), positionDetail));
    }
    
    0 回复  |  直到 6 年前