我有几个实体
@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;
}
示例:当我从回购中获取对象A并将新对象B添加到列表中时,存储库不会保存新对象B。
A a = aRepository.findById(someId);
B b = new B();
a.getB().add(B);
注意: Sql表不包含新的B。
答案 0 :(得分:1)
您应该将合并添加到层叠,仅在持久化时设置
只需添加CascadeType.MERGE
@JoinColumn(name = "a_id", referencedColumnName = "id")
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<B> b = new ArrayList<>();
答案 1 :(得分:0)
您的对象a
已经创建并且无法持久运行的主要问题并未发生。
如果您尝试使用某些A
元素创建(持久)新实体(B
),则新B
将包含在sql表中。