必须手动分配一对一ID

时间:2015-08-05 20:25:19

标签: java hibernate one-to-one

我想知道在保存一对一实体时如何制作Hibernate级联ID。

@Entity
@Table(name = "foo")
class Foo {
    @Id
    @Column(name = "foo_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "foo_seq")
    private Integer fooId;

    // ...

    @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "foo")
    private Bar bar;

    // ...

    public void setBar(Bar bar) {
        this.bar = bat;
        if (bar != null) {
            bar.setFoo(this);
            bar.setFooId(getFooId());
        }
    }

}

@Entity
@Table(name = "bar")
class Bar {

    @Id
    @Column(name = "foo_id")
    // this is the foo's id, the foreign key is the primary key of this table
    private Integer fooId;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Foo foo;

    // ...

}

好吧,当我保存Foo的实例没有Bar时,然后设置Bar的实例并再次保存它可行,但如果我尝试将其保存一次说ids for this class must be manually assigned before calling save

Foo foo = new Foo();
// foo.set...
repository.save(foo); // I do not want to save twice, I want to remove it
Bar bar = new Bar();
// bar.set...
foo.setBar(bar);
repository.save(foo);

如何解决此问题?我不需要它是双向的,但必须能够从Bar获得Foo,就像this thread中的讨论一样,但这次来自Foo表的id是相同的

1 个答案:

答案 0 :(得分:1)

它的行为是因为Hibernate在保存实体时生成 fooId 的值而不是之前。因此,即使您在setBar()方法中指定了 fooId ,它实际上也会将NULL分配给Bar.fooId,因为您还没有定义 Bar.fooId 上的生成策略您收到了该错误。修改下面给出的Bar类,然后再试一次,该错误应该消失:

 @Id
    @Column(name = "foo_id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer fooId;