亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用級聯保存父實體時如何獲取子實體 ID

使用級聯保存父實體時如何獲取子實體 ID

米琪卡哇伊 2023-03-31 09:19:24
我正在使用 spring-data-jpa。將子實體添加到父實體后,我將父實體保存到數據庫中。我想獲取孩子的id,但我發現我得到的是空的。我將 @GeneratedValue(strategy = GenerationType.IDENTITY) 添加到 getId() 方法,但它沒有用。這是模型:@Entitypublic class Parent {    private Integer id;    private List<Child> childList;    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    public Integer getId() {        return id;    }    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)    @JoinColumn(name = "parent_id")    public List<Child> getChildList() {        return childList;    }    // setters.....}@Entitypublic class Child {    private Integer id;    private String name;    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    public Integer getId() {        return id;    }    @Cloumn("name")    public String getName() {        return name;    }}父實體已經在數據庫中,所以我直接找到它, ParentRepository entends JpaReportory這里是我的測試代碼:Parent parent = parentRepository.findById(1);Child child = new Child();child.setName("child");parent.getChildList().add(child);parentRepository.save(parent);System.out.println("child's id: " + child.getId());我得到的輸出是:child's id: null孩子被保存到數據庫并且有id,但是實體在內存中的id仍然是空的,我如何在保存父母后得到孩子的id?而且因為我創建的孩子被其他對象引用,我需要只在這個孩子中獲取 id 而不是從數據庫中找到一個新對象。
查看完整描述

2 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

您必須使用保存方法的返回值:


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



查看完整回答
反對 回復 2023-03-31
?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

根據代碼,您已經創建了childObject 并且沒有為其元素設置任何值,然后嘗試從新創建的對象中獲取元素(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 行中,我們為其分配了 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



查看完整回答
反對 回復 2023-03-31
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號