In this example you will learn how to map many-to-one relationship using Hibernate. Consider the following relationship between Student and Address entity.
To create this relationship you need to have a STUDENT and ADDRESS table. The relational model is shown below.
To create the STUDENT and ADDRESS table you need to create the following hibernate mapping files.
Student.hbm.xml is used to create the STUDENT table.
01.<?xml version="1.0"?>02.<!DOCTYPE hibernate-mapping PUBLIC03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"05.<hibernate-mapping>06.<class name="com.vaannila.student.Student" table="STUDENT">07.<meta attribute="class-description">This class contains student details.</meta>08.<id name="studentId" type="long" column="STUDENT_ID">09.<generator class="native" />10.</id>11.<property name="studentName" type="string" length="100" not-null="true" column="STUDENT_NAME" />12.<many-to-one name="studentAddress"class="com.vaannila.student.Address" column="STUDENT_ADDRESS"cascade="all" not-null="true" />13.</class>14.</hibernate-mapping>
The many-to-one element is used to create the many-to-one relationship between the Student andAddress entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to all then all the operations will be cascaded. For instance when you save a Student object, the associated Address object will also be saved automatically.
Address.hbm.xml is used to create the ADDRESS table.
01.<?xml version="1.0"?>02.<!DOCTYPE hibernate-mapping PUBLIC03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"05.<hibernate-mapping>06.<class name="com.vaannila.student.Address" table="ADDRESS">07.<meta attribute="class-description">This class contains the student's address08.details.</meta>09.<id name="addressId" type="long" column="ADDRESS_ID">10.<generator class="native" />11.</id>12.<property name="street" column="ADDRESS_STREET" type="string"length="250" />13.<property name="city" column="ADDRESS_CITY" type="string" length="50"/>14.<property name="state" column="ADDRESS_STATE" type="string"length="50" />15.<property name="zipcode" column="ADDRESS_ZIPCODE" type="string"length="10" />16.</class>17.</hibernate-mapping>


No comments:
Post a Comment