Hibernate Tutorial

Hibernate Many to One tutorial with XML Based

Many to One Mapping XML based

A unidirectional many-to-one association is the most common kind of unidirectional association.

  1. <many-to-one name=“studentAddress” class=“com.candidjava.hibernate.Address”
  2. column=“STUDENT_ADDRESS” cascade=“all” />

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.candidjava.hibernate.Student" table="STUD1">
    <id name="studentId" type="long" column="ID">
      <generator class="increment" />
    </id>
    <property name="studentName" type="string" length="100"
      not-null="true" column="name" />
    <many-to-one name="studentAddress" class="com.candidjava.hibernate.Address"
      column="STUDENT_ADDRESS" cascade="all" />
  </class>
</hibernate-mapping>

Address.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.candidjava.hibernate.Address" table="ADDRESS1">
    <id name="addressId" type="long" column="aid">
      <generator class="increment" />
    </id>
    <property name="street" column="street" type="string" />
    <property name="city" column="city" type="string" />
    <property name="state" column="state" type="string" />
    <property name="zipcode" column="zip" type="string" />
  </class>
</hibernate-mapping>

save or inserting record into Many to One mapping

public void insertStudent(Student bk) {
    try {
      Session s = getSession();
      Transaction transaction = s.beginTransaction();
      s.save(bk);
      //s.save(b);
      transaction.commit();
 
    } catch (HibernateException e) {
      e.printStackTrace();
    }
  }

Get or fetch record from Many to One mapping

public Student getStudent(long id) {
    Student ls=new Student();	
    try {
      Session s = getSession();
      ls=(Student) s.load(Student.class,id);
       		} catch (HibernateException e) {
      System.out.println(e.getMessage());
    }
    return ls;
  }

Download

Hibernate Many to One war

Hibernate Many to One zip