Hibernate Many to One tutorial and example XML based


Many to One Mapping XML based


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


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


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="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





Comments


©candidjava.com