First, one-to-one (unidirectional): Use an external index to take one of the classes as the parent, the corresponding subclass, and reference the parent class's primary key ID to generate the database table. (For example, you can set a husband in the wife_id corresponding to the primary key ID in Wife) 1.Wife class: Generate Get, set method @Entity//Note Use annotations public class Wife {private int id; private S Tring name; @Id//Note Use annotations @GeneratedValue//note use annotations public int getId () {return Id;}} 2.Husband class, generate get, set method @Entity public class Husband {private int id; private String name; private Wife Wife; @Id @Generat Edvalue public int getId () {return ID,} public String GetName () {return name;} @OneToOne @JoinColumn (name= "wife_id")// Mapping: Set the name of the ID, if not set, the system defaults to a name public Wife Getwife () {return Wife;}}
Note: You can use Power Design (reverse engineering) to invert a database table table to see the effect.
Two, one-way (bidirectional): The same way, only in two classes should be set corresponding to another class (Private Husband Husband; Generates a Get Set method) but causes one of the additional associated indexes to be redundant and can be resolved by @onetoone (mappedby= "wife"). The equivalent to tell the system, to be wife-led, otherwise you will not find husband. 1.Wife class: Generate Get, set method @Entity public class Wife {private int id; private String name; private Husband husband;//Set Husband class An object and generates a Get.set method} Note: All bidirectional associations must be set Mappedby, but not necessary, because they are set once. 2.Husband class: Generate Get, set method @Entity public class Husband {private int id; private String name; private Wife Wife; @Id @Generat Edvalue public int getId () {return ID,} public String GetName () {return name;} @OneToOne (mappedby= "wife")//To be guided by wife Find husband Public Wife Getwife () {return Wife;}
Settings for the Hibernate.xml file: Note To register the newly created two classes in the mapping
<mapping class= "Com.cqvie.model.Husband"/> <mapping class= "Com.cqvie.model.Wife"/>
Hibrenate one-to-one foreign key association