Hibernate tutorial association one to many mapping using xml


One to Many Mapping XML based


A unidirectional One-to-many association on a foreign key is an unusual case, and is not recommended. Consider referring One to Many using Joins


<set name="studentPhone" cascade="all">
			<key column="stud_id" />
			<one-to-many class="com.candidjava.hibernate.Phone" />
		</set>



Code


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="student">
		<id name="studentId" column="sutid">
			<generator class="increment" />
		</id>
		<property name="studentName" column="stud_name" type="string" />
		<set name="studentPhone" cascade="all">
			<key column="stud_id" />
			<one-to-many class="com.candidjava.hibernate.Phone" />
		</set>

	</class>

	<class name="com.candidjava.hibernate.Phone" table="phone">
		<id name="phoneId" column="phone_id">
			<generator class="increment" />
		</id>
		<property name="phoneType" column="phone_type" type="string" />
		<property name="phoneNumber" column="phone_number" type="string" />

	</class>
</hibernate-mapping>


save or inserting record into One 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 One to Many mapping

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

Download

Hibernate One to Many war

Hibernate One to Many zip





Comments


©candidjava.com