Hi , I am trying to evaluate a mapping in this Hibernate document : section 2.2.3.1. Generating the identifier property
In the document , Person and MedicalHistory has @OneToOne mapping (MedicalHistory points to Person) , and the document suggests two mapping strategies :
First strategy :
@Entity
class MedicalHistory implements Serializable {
  @Id @OneToOne
  @JoinColumn(name = "person_id")
  Person patient;
}
@Entity
public class Person implements Serializable {
  @Id @GeneratedValue Integer id;
}
Second strategy :
@Entity
class MedicalHistory implements Serializable {
  @Id Integer id;
  @MapsId @OneToOne
  @JoinColumn(name = "patient_id")
  Person patient;
}
@Entity
class Person {
  @Id @GeneratedValue Integer id;
}
Everything works fine now , but...
To make things more complicated , I add another (3rd) table(class) that has a @ManyToOne relationship to MedicalHistory . And the first strategy will fail (while 2nd strategy still works).
I create another (3rd) class , naming MedicalLog , that has a @ManyToOne relationship to MedicalHistory :
@Entity
public class MedicalLog implements Serializable
{
  @Id @GeneratedValue
  private int id;
  @ManyToOne
  @JoinColumn(name="MedicalHistory_id")
  private MedicalHistory medicalHistory;
  private String action;      
  private Timestamp time;
  public MedicalLog(MedicalHistory mh , String action)
  {
    this.medicalHistory = mh;
    this.action = action;
  }
  // other methods
}
The exception occurs when hibernate initializes ... :
Caused by: org.hibernate.AnnotationException: A Foreign key refering destiny.play.MedicalHistory from destiny.play.MedicalLog has the wrong number of column. should be 0
at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:421)
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:111)
Personally , I love strategy 1 more , because it doesn't introduce another Integer id variable. And I feel Object id (strategy 2) is more comfortable (OO style).
Anyway , although strategy 2 works , but I wonder is there any way to make strategy 1 also work ?
Thanks a lot !
-- updated : table creation --
Table creation (MySQL) :
CREATE TABLE IF NOT EXISTS `Person` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `MedicalHistory` (
  `patient_id` int(10) NOT NULL,
  PRIMARY KEY (`patient_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `MedicalLog` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `MedicalHistory_id` int(10) NOT NULL,
  `action` varchar(15) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Hope it helps