Neuromante Neuromante - 1 month ago 9
Java Question

How does JPA knows how to link columns and entities with join-table?

Totally noob at JPA, I got this:

Three tables:

enter image description here

Also, a orm.xml file which describes their relationship:

<one-to-manyname="nombreAtributo"fetch=" {LAZY}">
<join-table schema="NOMBRE_SCHEMA" name = "TABLA1_TABLA2">
<join-column name="TABLA1_ID" referenced-column-name="ID" unique="true"/>
<inverse-join-column name="TABLA2_ID" referenced-column-name="ID"/>
</join-table>




(This snippet is inside its Tabla1 entity tag).

All right. The idea is having a list on TABLA1 of TABLA2 elements, so we "tell" through the ORM.xml file "Hey, nombreAtributo (in TABLA1) is the result of going through the TABLA1_TABLA2 relationship. TABLA1_ID is related to ID and TABLA2_ID to ID.

I get that what I'm actually saying is "TABLA1_ID is related to TABLA1.ID and TABLA2_ID is related to TABLA2.ID", but I fail to understand how JPA knows it. Is for the kind of relationship defined? For the names?

(And yeah, we are using xml's instead of annotations)

Answer

All is written in the javadoc of JoinTable :

Annotation Type JoinTable

Specifies the mapping of associations. It is applied to the owning side of an association.

So, according to the below xml mapping for TABLA1 entity, the entity which owns the relation is TABLA1 :

<one-to-manyname="nombreAtributo"fetch=" {LAZY}">
 <join-table schema="NOMBRE_SCHEMA" name = "TABLA1_TABLA2">
      <join-column name="TABLA1_ID" referenced-column-name="ID" unique="true"/>
      <inverse-join-column name="TABLA2_ID" referenced-column-name="ID"/>
  </join-table>

joinColumns

(Optional) The foreign key columns of the join table which reference the primary table of the entity owning the association. (I.e. the owning side of the association).

So, the join-column TABLA1_ID reference the PK of TABLA1 since TABLA1 owns the association.

inverseJoinColumns

(Optional) The foreign key columns of the join table which reference the primary table of the entity that does not own the association. (I.e. the inverse side of the association).

So, inverse-join-column TABLA2_ID references the PK of TABLA2 since TABLA2 doesn't own the association.