Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want a unidirectional one-to-one relationship between objects of 3 java classes: Person to Heart, and Person to Liver. I want the objects to share the same PK i.e. every person has a corresponding heart and liver, where person.person_id = heart.heart_id = liver.liver_id. I do not want to merge the 3 tables into 1 because each has loads of fields. Here's my code (mostly based on the accepted answer for this question):

@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;}

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

   // other getters and setters and constructors
}


@Entity
public class Heart {
   private long heartId;
   private int bpm;
   private Person person;
   // other fields

   @Id
   @GenericGenerator(
      name = "generator",
      strategy = "foreign",
      parameters = @Parameter(name = "property", value = "person")
   )
   @GeneratedValue(generator = "generator")
   public long getHeartId() {return heardId;}

   @OneToOne(mappedBy="heart")
   @PrimaryKeyJoinColumn
   public Person getPerson() {return person;}

   // other getters and setters and constructors
}


@Entity
public class Liver {
   private long liverId;
   private boolean healthy;
   private Person person;
   // other fields

   // the rest uses the same hibernate annotation as Heart
}

I setup the session and do the following:

Person jack = new Person();
jack.setName("jack");
Heart heart = new Heart();
heart.setBpm(80);
Liver liver = new Liver();
liver.setHealthy(true);

Then if I link up the person object with it's organs, and save it, I get an error (NOTE: I got the same behaviour when I just used 2 classes e.g. Person and Heart):

jack.setHeart(heart);
jack.setLiver(liver);
session.save(jack);

org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property: person

However it works if I set the relationship both ways:

jack.setHeart(heart);
heart.setPerson(jack);
jack.setLiver(liver);
liver.setPerson(jack);
session.save(jack);

But surely this should not be necessary for unidirectional relationships?
Cheers

ps. Oddly enough, I notice it works (saves both objects to the DB) when I just use 2 classes e.g. Person and Heart, and I just set the link the other way:

heart.setPerson(jack);
session.save(heart);

I have no idea why this works (it seems logical to me that Person is the parent object, as it auto-generates it's own PK, and the others use that; so that's all you should have to setup), but anyway I cannot figure out how to apply this working method to my 3-class situation...

like image 411
jackocnr Avatar asked Dec 08 '09 14:12

jackocnr


People also ask

What is a one-to-one relationship in hibernate?

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. In this tutorial, we show you how to work with one-to-one table relationship in Hibernate, via XML mapping file (hbm).

Can we manage both ends of an association in hibernate?

We should not make both ends of association “managing the relationship”. Never do it. While Hibernate lets us specify that changes to one side of the association will result in changes to the database, it does not allow us to cause changes to one end of the association to be automatically reflected.

What is one to one mapping in hibernate?

Hibernate - One-to-One Mappings, A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example, an address object can be as Home Coding Ground Jobs Whiteboard Tools Business Teach with us Login Category Academic Tutorials Big Data & Analytics Computer Programming

How to generate the primary key in hibernate?

The <generator>element within the id element is used to generate the primary key values automatically. The classattribute of the generator element is set to nativeto let hibernate pick up either identity, sequenceor hiloalgorithm to create primary key depending upon the capabilities of the underlying database.


2 Answers

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
}
like image 194
BryanD Avatar answered Oct 09 '22 12:10

BryanD


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

like image 23
KLE Avatar answered Oct 09 '22 13:10

KLE