Spring Data does not save related entity

Viewed 600

I have several entities

@Entity
@Table(name = "A")
public class A {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "alIdSeq")
    @SequenceGenerator(name = "aIdSeq", sequenceName = "a_id_seq", allocationSize = 1)
    private Long id;

    @JoinColumn(name = "a_id", referencedColumnName = "id")
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    private List<B> b = new ArrayList<>();

}
@Entity
@Table(name = "B")
public class B {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "blIdSeq")
    @SequenceGenerator(name = "aIdSeq", sequenceName = "b_id_seq", allocationSize = 1)
    private Long id;

}

Example: When I get object A from repo and add new object B to list then repository does not save new object B.

A a = aRepository.findById(someId);
B b = new B();
a.getB().add(B);

Note: Sql table does not contain new B.

2 Answers

The main problem that your object a already created, and persisted operation didn't happen. If you try to create (persist) new entity (A) with some B elements, new B will contains in sql table.

You should add the merge to cascade , it is set only on persist

just add CascadeType.MERGE

@JoinColumn(name = "a_id", referencedColumnName = "id")
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<B> b = new ArrayList<>();
Related