首页 > 解决方案 > Spring Data 不保存相关实体

问题描述

我有几个实体

@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;

}

示例:当我从 repo 获取对象 A 并将新对象 B 添加到列表时,存储库不会保存新对象 B。

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

注意: sql表不包含new B。

标签: javaspringpostgresqljpaspring-data

解决方案


您的对象a已经创建并且持久操作的主要问题没有发生。如果您尝试A使用某些B元素创建(持久)新实体(),则 newB将包含在 sql 表中。


推荐阅读