Hibernate Tutorial

Hibernate many to many mapping using XML Tutorial

Many to Many Mapping XML based

A unidirectional Many-to-many association mappings need 3 tables, the intermediate table contains primary key of both the entity. But Many to Many is not recommended since most of the use case the intermediate need to maintain some extra data like createdby etc..

<set name="courses" table="SCOURSE" cascade="all">
      <key column="SID" />
      <many-to-many column="CID" class="com.candidjava.hibernate.Course" />
    </set>

 

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="STUDENT3">
    <id name="studentId" type="long" column="SID">
      <generator class="native" />
    </id>
    <property name="studentName" type="string" not-null="true"
      length="100" column="SNAME" />
    <set name="courses" table="SCOURSE" cascade="all">
      <key column="SID" />
      <many-to-many column="CID" class="com.candidjava.hibernate.Course" />
    </set>
  </class>
</hibernate-mapping>

Course.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.Course" table="COURSE">
    <id name="courseId" type="long" column="CID">
      <generator class="native" />
    </id>
    <property name="courseName" type="string" column="CNAME" />
  </class>
 
</hibernate-mapping>

save or inserting record into Many to Many mapping

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

Get or fetch record from Many to Many mapping

public Student getStudents(long id) {
    Student sd = null;
    try {
      Session s = getSession();
 
      sd = (Student) s.get(Student.class, id);
            
    } catch (HibernateException e) {
      System.out.println(e.getMessage());
    }
    return sd;
  }

Download

Hibernate Many to Many war

Hibernate Many to Many zip