2 回答

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
您必須使用保存方法的返回值:
Parent parent = parentRepository.findById(1);
Child child = new Child();
parent.getChildList().add(child);
parent = parentRepository.save(parent); <---------- use returned value with ids set
System.out.println("child's id: " + parent.getChildList().get(0).getId()); <-- access saved child through parent list

TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
根據(jù)代碼,您已經(jīng)創(chuàng)建了childObject 并且沒有為其元素設(shè)置任何值,然后嘗試從新創(chuàng)建的對象中獲取元素(child.getId())它將始終為 null,除非您將 DB 中的值分配給它。
Parent parent = parentRepository.findById(1);
Child child = new Child(); // Empty child object created
parent.getChildList().add(child);
parentRepository.save(parent);
System.out.println("child's id: " + child.getId()); //Referring empty child object
在這里您可以做的是:
在第 5 行中,我們?yōu)槠浞峙淞?dB 值
Parent parent = parentRepository.findById(1);
Child child = new Child(); // Empty child object created
parent.getChildList().add(child);
parent = parentRepository.save(parent);
child = parent.getChildList().get(0);// assing db value to it( assingning 1st value of `ChildList`)
System.out.println("child's id: " + child.getId()); //now Referring non-empty child object
添加回答
舉報(bào)