Wednesday, October 28, 2009

Hibernate many-to-one example

Basic many-to-one
<class
  name="Student"
  table="STUDENT"> Many students have the same course
  ...
  <many-to-one>
    name="course"
student has a property by name "course"
    column="COURSE_ID" COURSE_ID is a foreign key in STUDENT table.
    "column" is Optional. If not specified, target entity name ("course") + "_" + target entity if property name is default.
    class="Course" Optional. If not specified, hibernate will figure out from type of property.
    not-null="true"/> Each student MUST have a course
</class>

public class Student
{
  private Course course; // with getters and setters
  ...
}

"unique" in many-to-one

<class
  name="Student"
  table="STUDENT">
  ...
  <many-to-one>
    name="course"

    column="COURSE_ID"
    class="Course"

    not-null="true"
    unique="true"/> 
Each student MUST have a UNIQUE course. Does not make  sense in this example as that would mean each student must have a unique course i.e.  only one student can study a course. :-)
</class>


No comments: