Set one-to-one foreign key associations. You can find the wife through husband, but cannot find husband through wife.
1. Write the entity class wife;
When annotation is used, the entity class is annotated, @ entity, @ ID
Package COM. hibernate. _ 0600_one2one_uni_fk; import javax. persistence. entity; import javax. persistence. ID; @ entitypublic class wife {private integer ID; private string name; @ idpublic integer GETID () {return ID;} public void setid (integer ID) {This. id = ID;} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}
2. Compile the husb and class and add the wife reference to husb and;
Package COM. hibernate. _ 0600_one2one_uni_fk; import javax. persistence. entity; import javax. persistence. generatedvalue; import javax. persistence. ID; import javax. persistence. joincolumn; import javax. persistence. onetoone;/** one-to-one external Association, */@ entitypublic class husband {private integer ID; private string name; private wife; // refer to the wife ID, in this case, wife must first ID @ generatedvaluepublic integer GETID () {return ID;} Public String getname () {return name ;} @ onetoone // set the link @ joincolumn (name = "wifeid") // @ joincolumn connection field. Specify the database name. The default value is wife_idpublic wife getwife () {return wife;} public void setid (integer ID) {This. id = ID;} public void setname (string name) {This. name = Name;} public void setwife (wife) {This. wife = wife ;}}
Add the wife reference to husb and reference the wife ID;
When annotation is used, the entity class is annotated, @ entity, @ ID;
Add annotations and set the link to @ onetoone;
@ Joincolumn annotation can be used to set the field names of foreign keys in the database, or specify the length and type;
3. Write a test class, generate a database table, and view the table relationship;
Public class ormtest {Private Static sessionfactory; @ beforeclasspublic static void beforeclass () {sessionfactory = new annotationconfiguration (). configure (). buildsessionfactory ();} @ afterclasspublic static void afterclass () {sessionfactory. close () ;}@ testpublic void testschemaexport () {New schemaexport (New annotationconfiguration (). configure ()). create (false, true );}}
4. Add the class label to the XML file
<Role-to-one name = "wife" column = "wifeid" unique = "true"> </role-to-one>
Unique = "ture" is bound to one-to-one association;