首页 > 解决方案 > 将 OneToOne 链接更改为具有另一个 ID 的另一个实体

问题描述

有一个问题,在任何地方都找不到答案 =)

我有实体包装

@Entity
public class Packing {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_packing")
    @SequenceGenerator(allocationSize = 100, name="seq_packing", sequenceName="seq_packing")
    @Getter
    long id;

    @Getter
    @Setter
    @OneToOne
    PackingDictionary packingDictionary;

    @Getter
    @Setter
    long price;

    @Getter
    @Setter
    long quantity;

    public Packing() {
    }

    public Packing(PackingDictionary packingDictionary, long price, long quantity) {
        this.packingDictionary = packingDictionary;
        this.price = price;
        this.quantity = quantity;
    }

    public void changePackingType(Long id){

    }
}

我使用 OneToOne 关系在 Packing 实体和 PackingDictionary(实际上是字典)之间进行引用。

那么如何创建一个方法来更改对 Dictionary 中已经存在的另一个 id 的引用?

在 SQL 中,它将只是更改 PACKING 表中的参考 ID。

标签: javaspring-data-jpareferenceone-to-one

解决方案


packingRepository.findById(id)
   .ifPresent(packing -> packing.setPackingDictionary(packingDictionaryRepository.getOne(dictionaryId)) 

推荐阅读