Search code examples
javaspring-data-jpareferenceone-to-one

Change OneToOne link into another entity with another id


Got a question and can't find an answer anywhere =)

I have entity Packing

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

    }
}

I use the OneToOne relation to make a reference between Packing entity and PackingDictionary (that is really dictionary).

So how can I make a method that will change a reference to another id in Dictionary that already exists?

In SQL it will be just changing reference id in PACKING table.


Solution

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