使用级联保存父实体时如何获取子实体 ID

我正在使用 spring-data-jpa。将子实体添加到父实体后,我将父实体保存到数据库中。我想获取孩子的id,但我发现我得到的是空的。


我将 @GeneratedValue(strategy = GenerationType.IDENTITY) 添加到 getId() 方法,但它没有用。


这是模型:


@Entity

public 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.....


}


@Entity

public 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 而不是从数据库中找到一个新对象。


米琪卡哇伊
浏览 68回答 2
2回答

紫衣仙女

您必须使用保存方法的返回值:Parent parent = parentRepository.findById(1);Child child = new Child();parent.getChildList().add(child);parent = parentRepository.save(parent); <---------- use returned value with ids setSystem.out.println("child's id: " + parent.getChildList().get(0).getId()); <-- access saved child through parent list

神不在的星期二

根据代码,您已经创建了childObject 并且没有为其元素设置任何值,然后尝试从新创建的对象中获取元素(child.getId())它将始终为 null,除非您将 DB 中的值分配给它。Parent parent = parentRepository.findById(1);Child child = new Child(); // Empty child object createdparent.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 createdparent.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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java