javahibernatejpaone-to-one

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

Which 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


Solution

  • 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 ?