Вы находитесь на странице: 1из 3

2017430 javaWhydoIneedthethirdtableformanytomanymapping?Whycan'tIjustusetwotables?

StackOverflow

WhydoIneedthethirdtableformanytomanymapping?Whycan'tIjustusetwotables?

Ihavebeentrying manytomany relationshipbetweentwoclasses Person and Address .Idon'tknowbutsomewhereIamnotthinkingalongthe


correctlines.Forexampleformanytomanymapping,Imadetwotables

CREATETABLEperson(p_idINTEGER,p_nameTEXT,PRIMARYKEY(p_id));
CREATETABLEaddress(a_idINTEGER,addressTEXT);

andthenItriedsomethinginthemappingxml.AftersomeunsuccessfulattemptsIreadthatyouneedthreetablesformanytomanymapping,
justasananswertooneofmyquestionsays.

Pleaseexplainmethereasonforthis?WhydoIneedthethirdtable?WhycannotImakeanassociationjustwiththetwotables?

java hibernate manytomany hibernatemapping

askedJun25'13at8:32
SuhailGupta
6,853 42 113 201

whyadownvote? SuhailGupta Jun25'13at8:34


CosthisisverybasicstuffthatyoushouldeasilybeabletolookupZutty Jun25'13at8:38

@Zutty.Douknowtheanswer..ifsopostyoucanpost..Formeit'sagoodquestion.kark Dec16'13at
12:53

4Answers

Thethirdtableservesasajunctiontablethatdefinesthemanytomanyrelationship.Inyour
exampleIassumethata Person canhavemultiple addresses andanaddresscanbelongto
multiple People .Thisrelationshipcannotbemodeledusingtwotables.

Youmayattempttosimplyincludeaforeignkeytothe Address inthe Person tableoraforeign


keyto Person inthe Address table.Eachofthesemappingswouldhavea one side,meaning
one oftheparticularentitiescorrespondswith many oftheother.Noneoftheseoptionsachieve
the manytomany relationshipandtheuseofathirdtableisrequiredtomapthemorecomplex
relationship.

Inordertomapasa manytomany youneedtobeabletoassociatemultipleinstancesofboth


entitieswitheachother.Thisistraditionallydoneviathefollowing:

TableA
ID_A

TableB
ID_B

TableC
ID_A
ID_B

editedJun25'13at8:41 answeredJun25'13at8:35
KevinBowersox
67.2k 8 96 126

Becauseofthenatureoftherelation.

Ifthemappingwasonetoone,thanyoucouldadda person_id columntothe Address table


andeach Address tuplewouldpointtojustone Person .

Address
++
|id|p_id|address|
++
|1|1|somestreet1|//oneaddressuniquelypointstooneperson
++
|2|2|newstreet5|
++

http://stackoverflow.com/questions/17292648/whydoineedthethirdtableformanytomanymappingwhycantijustusetw 1/3
2017430 javaWhydoIneedthethirdtableformanytomanymapping?Whycan'tIjustusetwotables?StackOverflow

Samegoesforonetomany:ifa Person canhavemultiple Address es,thentherewouldbe


multipletuplesin Address tablewiththesame person_id .

Address
++
|id|p_id|address|
++
|1|1|somestreet1|//twoaddressespointtooneperson
++
|2|1|newstreet5|
++

Butwhatifone Person canhavemutliple Address es,butalso,one Address canbelongto


multiple Person s?Thenonecolumn person_id inthe Address tablewouldnotbeenough
becauseone Address canrelatetomany Person s!Soyouneedathirdtabletoassociateall
pairsof Person sand Address es.

Assoctable
++
|a_id|p_id|
++
|1|1|//oneaddressfortwopersons
++
|1|2|
++
|2|3|//twoaddressesforthesameperson
++
|3|3|
++

answeredJun25'13at8:37
darijan
8,229 15 32

HmmmI'mnotsurebutIthinkhe'stalkingaboutcreatinga"thirdclass"inhismappingandnot
really"thirdtable"(otherwisehewouldn'teventalkabouthibernatemapping).SoIwillassume
thathe'sjuststrugglingwithhismappingformyanswer(anditwillstillbeusefullaterforhis
hibernatemapping):

Thankstothe@JoinTableannotationyoudon'thavetocreateanentityforthethirdtable.Ifyou
haveamanytomanyrelationshipbetweenyourtables,youjusthavetocreate2entities
"Person"and"Address",andthe@JoinTableannotationoneachsidewillapplythemanyto
manymagicwithouthavingtocreateanentityforthethirdtablebetweenthem.

EXCEPTifyourthirdtablehavesomeextracolumns,andtheninthatcaseyoudon'thavea
choiceyouwillhavetocreateaspecificentityforthisthirdtable(orotherwiseyoucan'tgetthat
extracolumnwithjust"Person"and"Address"entities).

Someusefullinksforyourmapping:

http://www.mkyong.com/hibernate/hibernatemanytomanyrelationshipexampleannotation/
http://www.mkyong.com/hibernate/hibernatemanytomanyexamplejointableextracolumn
annotation/

answeredJun25'13at8:49
JrmeSengel
55 1 9

ImusingManyToManywithJPAannotation,Ineedyourvaluablesuggestions.(AssumePerson
andAddress.SameAddressisreferredtomoreperson(livingatsameaddress)).Ihaveto
deleteapersonfromthataddress.

Personp1=newPerson();
Personp2=newPerson();
Addressadd1=newAddress();

p1.add(add1);
p2.add(add1);

Usingsameaddreftobothpersons.Aswelldoing

add1.add(p1);
add1.add(p2);

THenonmergeorpersistiitmappedappropriately.

p1add1p2add1

http://stackoverflow.com/questions/17292648/whydoineedthethirdtableformanytomanymappingwhycantijustusetw 2/3
2017430 javaWhydoIneedthethirdtableformanytomanymapping?Whycan'tIjustusetwotables?StackOverflow
Ihavetodeletep2alone,whenidid

p2.removeAddress(add1)
removeAddress(add1){coll.remove(add1)}

WhathappensisitdeletedtheentryforaddressandagainbyHibernatejpaprovideragaintries
topersistatAddressentityandsays"deletedentitypassedtopersist"andhenctransactionroll
backhappens.Iwasvingmapingas

@ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JoinTable(name="XXXX",joinColumns={@JoinColumn(name="X1_ID",nullable=
false,updatable=false)},inverseJoinColumns={@JoinColumn(name="X2_ID",nullable=
false,updatable=false)})
privateCollection<Parser>parsers;

Pleaseshareyourideas.

editedJan15'14at6:43 answeredJan8'14at13:11
Marie
11 1 5

http://stackoverflow.com/questions/17292648/whydoineedthethirdtableformanytomanymappingwhycantijustusetw 3/3

Вам также может понравиться