One to One Mapping XML based
A unidirectional one-to-one association uses the relationship student and address
<one-to-one name="address" class="com.candidjava.hibernate.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" /> <one-to-one name="address" class="com.candidjava.hibernate.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">
<param name="property">s</param>
</generator>
</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 One 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 One 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