Cherry
Cherry

Reputation: 33618

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?

Upvotes: 1

Views: 1337

Answers (1)

Victor
Victor

Reputation: 51

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

Upvotes: 1

Related Questions