Question

I downloaded a Hibernate one-to-many example which had the following mapping file:

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <set name="certificates" cascade="all">
         <key column="employee_id"/>
         <one-to-many class="Certificate"/>
      </set>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>

   <class name="Certificate" table="CERTIFICATE">
      <meta attribute="class-description">
         This class contains the certificate records. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="name" column="certificate_name" type="string"/>
   </class>

</hibernate-mapping>

The program runs smoothly but I am new to Hibernate, I just want to understand that employee information is stored in table EMPLOYEE, certificate's information is stored in table CERTIFICATE, now because one employee can have many certificates we used one-to-many mapping i.e. by adding this to the mapping file:

  <set name="certificates" cascade="all">
     <key column="employee_id"/>
     <one-to-many class="Certificate"/>
  </set>

But now what I want to understand is that when we fetch a record from table EMPLOYEE how am I able to access the certificates of that employee, what I don't understand is that my table EMPLOYEE has only four columns 'id', 'firstname', 'lastname' and 'salary' so how come when I fetch a record the object comes with certifications as well.

In a many to many situation, typically a linking(intermediate) table is used. This allows SQL or whatever database to maintain the relationships and hibernate simply relies on the mapping to pull the right stuff out of the database. But how does it manage with one-to-many mapping

Was it helpful?

Solution

In your case employeeId will be available in the Certificate table. It will work as a foreign key to the employee table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top