Hibernate one-to-one entity association with shared PK between 3 classes

喜你入骨 提交于 2019-12-03 14:34:28

I hate to tell you this, but you have a bi-directional relationship there. The Person has a reference to the Heart and Liver and each of those have a reference back to the Person. The annotations that you have set up on the Id properties of your Heart and Liver are specifically saying that they get the value of their Id property by delegating to their Person property. In the examples that you've shown that don't work, you haven't set the Person property on those guys yet and so, they obviously cannot obtain their Id value.

You can either set this relationship up as a true unidirectional OneToOne, which is documented in the Hibernate annotations documentation:

@Entity
public class Body {
    @Id
    public Long getId() { return id; }

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    public Heart getHeart() {
        return heart;
    }
    ...
}


@Entity
public class Heart {
    @Id
    public Long getId() { ...}
}

or you can change our entity objects slightly to streamline hooking up both sides of the relationship such as:

@Entity
public class Person {
   public long personId;
   private String name;
   public Heart heart;
   public Liver liver;
   // other fields

   @Id
   @GeneratedValue
   public long getPersonId() {return personId;}

   @OneToOne(cascade = CascadeType.ALL)
   @PrimaryKeyJoinColumn
   public Heart getHeart() {return heart;}

   public void setHeart(Heart heart){
      this.heart = heart;
      this.heart.setPerson(this);
   }

   @OneToOne(cascade = CascadeType.ALL)
   @PrimaryKeyJoinColumn
   public Liver getLiver() {return liver;}

   public void setLiver(Liver liver){
      this.liver = liver;
      this.liver.setPerson(this);
   }
   // other getters and setters and constructors
}

I didn't try it, but I would say that ....

A difference between both sides is that the Person class has no mappedBy in his mapping.

So, for each One-To-One, Person has the reference value, the one that Hibernate consider as official. On the contrary, on the other objects, the mappedBy indicates to Hibernate to not use the value, but go to that object and consider the mapped property on the that object.


To check if I'm right, you could set only the values that have no mappedBy, and save the Person object (because it is the one that has the cascades), and see if the result is correct.. ;-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!