简体   繁体   中英

How persist new created parent and child entities with hibernate?

Here is entities:

@Entity
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent" ,cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    private Collection<Child> children;
}

@Entity
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    private Parent parent;

}

For managing this entities I use spring data (rest). I need to save entities like that:

Parent parent = new Parent();
Child child = new Child()
parent.setChildren(Arrays.asList(child))
springDataRepository.save(parent);

And only Parent object is persisted.

Also as I spot parent and child are created without id . So should I persist only parent , then set it to child and persist child ? Can these operation be done with one parent saving action?

See this reply: https://stackoverflow.com/a/7428143

Instead of:

parent.setChildren(Arrays.asList(child))

you should use:

parent.setChildren(new ArrayList<>(Arrays.asList(child)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM