Search

Hibernate Many-To-One Mapping Example part -3

01.package com.vaannila.student;
02. 
03.import org.hibernate.HibernateException;
04.import org.hibernate.Session;
05.import org.hibernate.Transaction;
06. 
07.import com.vaannila.util.HibernateUtil;
08. 
09.public class Main {
10. 
11.public static void main(String[] args) {
12.Session session = HibernateUtil.getSessionFactory().openSession();
13.Transaction transaction = null;
14.try {
15.transaction = session.beginTransaction();
16.Address address = new Address("OMR Road""Chennai""TN","600097");
17.//By using cascade=all option the address need not be saved explicitly when the student object is persisted the address will be automatically saved.
18.//session.save(address);
19.Student student1 = new Student("Eswar", address);
20.Student student2 = new Student("Joe", address);
21.session.save(student1);
22.session.save(student2);
23.transaction.commit();
24.catch (HibernateException e) {
25.transaction.rollback();
26.e.printStackTrace();
27.finally {
28.session.close();
29.}
30. 
31.}
32. 
33.}
On executing the Main class you will see the following output.
The Student table has two records.
The Address table has one record.
Both the student records points to the same address record, this illustrates the many-to-one mapping.
Download Hibernate examples source code

No comments:

Post a Comment