小编Jil*_*ill的帖子

CascadeType.Persist 未按预期工作

我有以下代码(当然是简化的):

 @Entity
 public class Foo {
   @Generated
   private Long id;
   @OneToMany(mappedBy=foo)
   @Cascade(CascadeType.PERSIST)
   private Collection<Bar> bars;
   ...
 }

 @Entity
 public class Bar {
   @Generated
   private Long id;
   @ManyToOne
   @NotNull
   private Foo foo;
   ...
 }
Run Code Online (Sandbox Code Playgroud)

从我见过的许多例子来看,这应该有效:

 Foo foo = new Foo();
 Bar bar = new Bar();
 bar.setFoo(foo);
 Bar bar2 = new Bar();
 bar2.setFoo(foo);
 foo.bars.add(bar);
 foo.bars.add(bar2);
 hibernateTemplate.save(foo);
Run Code Online (Sandbox Code Playgroud)

当我说“这应该有效”时,我的意思是我期望发生的是,当我查看数据库表 Foo 时,我将有一行 Foo (假设 id =1 )和两行 Bar,每行都有foo_id 列中的值 1(foo 的 id)。

现实中发生的事情是我得到一个异常:

org.hibernate.PropertyValueException: not-null property references a null or transient   value:
Run Code Online (Sandbox Code Playgroud)

在 Bar.foo 上。如果我删除 …

java spring annotations hibernate

2
推荐指数
1
解决办法
8913
查看次数

标签 统计

annotations ×1

hibernate ×1

java ×1

spring ×1