简体   繁体   中英

Save id in both entities via Hibernate + JPA

I have two entities that have a relation OneToOne, like this:

@Entity
@Table(name = "FOO")
Foo{

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "foo")
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    @JoinColumn(name = "BAR_ID")
    private Bar bar;

    // getters and setters
 }

 @Entity
 @Configurable
 @Table(name = "BAR")
 Bar{
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "FOO_ID")
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    private Foo foo;

    // getters and setters
 }

In the Service layer, I make the connection by setting Bar in Foo:

 Bar.setFoo(foo);
 barDAO.saveOrUpdate(bar);

Wich saves the foo id in the Bar table. But the opposite doesn't happen. Is it possible for hibernate to save both ids making only one set? I thought this would be working already

You are missing the opposite side of the relation.

If you say bar.setFoo(foo) then after you have to say foo.setBar(bar) or of course you can do this within the setFoo method as well.

Cascading means that it will trigger the operation on the relation, however in your case, the relation was unfinished as one side was missing.

You need to understand the relationships well first. As much I see here you might trying to have a bidirectional OneToOne relationship between Foo and Bar .

@Entity
@Table(name = "FOO")
Foo {

     @OneToOne(cascade = CascadeType.ALL)
     @JoinColumn(name = "BAR_ID")
     private Bar bar;

     // getters and setters
}

@Entity
@Table(name = "BAR")
Bar{

    @OneToOne(mappedBy = "bar")
    private Foo foo;

    // getters and setters
}

In the bidirectional association two sides of association exits – owning and inverse. For one to one bidirectional relationships, the owning side corresponds to the side that contains the appropriate foreign key.

Here the owning side is the Foo and BAR_ID would be that foreign key. Having join column in both end doesn't make sense. And Relation will be cascaded from the Foo to Bar . And the inverse side is Bar here that needs to be annotated with mapped by value of the owning side reference.

Now if you set Bar object in Foo it will persist the Bar object along with the mapping with Foo . Doing the reverse thing doesn't make sense. isn't it ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM