Search

Hibernate Component Mapping Example Part -2


01.package com.vaannila.student;
02. 
03.// Generated Sep 3, 2009 6:57:20 PM by Hibernate Tools 3.2.4.GA
04. 
05./**
06.* This class contains student details.
07.*/
08.public class Address implements java.io.Serializable {
09. 
10.private String street;
11.private String city;
12.private String state;
13.private String zipcode;
14. 
15.public Address() {
16.}
17. 
18.public Address(String street, String city, String state, String zipcode) {
19.this.street = street;
20.this.city = city;
21.this.state = state;
22.this.zipcode = zipcode;
23.}
24. 
25.public String getStreet() {
26.return this.street;
27.}
28. 
29.public void setStreet(String street) {
30.this.street = street;
31.}
32. 
33.public String getCity() {
34.return this.city;
35.}
36. 
37.public void setCity(String city) {
38.this.city = city;
39.}
40. 
41.public String getState() {
42.return this.state;
43.}
44. 
45.public void setState(String state) {
46.this.state = state;
47.}
48. 
49.public String getZipcode() {
50.return this.zipcode;
51.}
52. 
53.public void setZipcode(String zipcode) {
54.this.zipcode = zipcode;
55.}
56. 
57.}
Create the Main class to run the example.

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.Student student = new Student("Eswar", address);
18.session.save(student);
19.transaction.commit();
20.catch (HibernateException e) {
21.transaction.rollback();
22.e.printStackTrace();
23.finally {
24.session.close();
25.}
26. 
27.}
28. 
29.}
On executing the Main class you will see the following output.

Each student has one address and the values are stored in the same STUDENT table.
The folder structure of the example is shown below.









No comments:

Post a Comment