您的位置:首页 > 其它

Hibernate -- A unidirectional one-to-one association on a foreign key

2014-01-11 15:17 267 查看
atsometimeweusuallyneedtocreatetwotablesthatonetablerelateanother.Suchasahusbandonly

haveawife.SohowcanIdesignrelationshiplikethis.Inprogramming,Thetypeofthisrelationship

named“unidirectionalone-to-oneassociation”.

Howtoimplementthisrelationshipwithhibernate?

exampleforhusbandandwife.

Whencreateobjecthusbandandwife,youcanrelatetwoobjectlikethis:

TheHasbandobject:

@Entity

[code]publicclassHusband{
privateintid;

privateStringname;

privateWifewife;

@Id

@GeneratedValue

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

@OneToOne

@JoinColumn(name="wifeId")

publicWifegetWife(){

returnwife;

}

publicvoidsetWife(Wifewife){

this.wife=wife;

}

}

[/code]

TheWifeobject:

@Entity

[code]publicclassWife{
privateintid;

privateStringname;

@Id

@GeneratedValue

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}


}

[/code]

Weuseannotationconfigurationhibernatebydefault.Soyousawtheannotitionlike@Entityincode.

WifeandHusbandbothareused@Entity.Itmeansthatobjectwillmappingtodatabase.

ThegetId()methodinWifeandHusbandbothareused@Idand@GeneratedValue

ThegetWife()methodinHusbandobjecthasannotationlikethis:

@OneToOne
@JoinColumn(name="wifeId")

Then,thecolumnwhichisnamedwifeIdwillebecreated.

So,Useannotationissosimple.that;sall.

DofromthatwecangetcreatetableSQLlikethis:


createtableHusband(

[code]idintegernotnullauto_increment,
namevarchar(255),

wifeIdinteger,

primarykey(id)

)

2014-1-1114:46:41org.hibernate.tool.hbm2ddl.SchemaExportperform



createtableWife(

idintegernotnullauto_increment,

namevarchar(255),

primarykey(id)

)


altertableHusband

addconstraintFK_kruq9jfxa0jrc2od8dbh09mia

foreignkey(wifeId)

referencesWife(id)

[/code]

Finally,Talkaboutxmlconfigure.Whenusexmltoconfigurehibernatemoretroublethanuseannotations:

Youneedwritelikethisinxmlfile:

<many-to-onename="wife"column="wifId"unique="true"></many-to-one>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐