Thursday 23 August 2012

Hibernate Mapping Many-to-One using Annotations Tutorial


In this example you will learn how to map many-to-one relationship using Hibernate Annotations. Consider the following relationship between Student and Address entity.

According to the relationship many students can have the same address.
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 Java classes with hibernate annotations.
Student class is used to create the STUDENT table.
01.package com.vaannila.student;
02. 
03.import javax.persistence.CascadeType;
04.import javax.persistence.Column;
05.import javax.persistence.Entity;
06.import javax.persistence.GeneratedValue;
07.import javax.persistence.Id;
08.import javax.persistence.ManyToOne;
09.import javax.persistence.Table;
10. 
11.@Entity
12.@Table(name = "STUDENT")
13.public class Student {
14. 
15.    private long studentId;
16.    private String studentName;
17.    private Address studentAddress;
18. 
19.    public Student() {
20.    }
21. 
22.    public Student(String studentName, Address studentAddress) {
23.        this.studentName = studentName;
24.        this.studentAddress = studentAddress;
25.    }
26. 
27.    @Id
28.    @GeneratedValue
29.    @Column(name = "STUDENT_ID")
30.    public long getStudentId() {
31.        return this.studentId;
32.    }
33. 
34.    public void setStudentId(long studentId) {
35.        this.studentId = studentId;
36.    }
37. 
38.    @Column(name = "STUDENT_NAME", nullable = false, length = 100)
39.    public String getStudentName() {
40.        return this.studentName;
41.    }
42. 
43.    public void setStudentName(String studentName) {
44.        this.studentName = studentName;
45.    }
46. 
47.    @ManyToOne(cascade = CascadeType.ALL)
48.    public Address getStudentAddress() {
49.        return this.studentAddress;
50.    }
51. 
52.    public void setStudentAddress(Address studentAddress) {
53.        this.studentAddress = studentAddress;
54.    }
55. 
56.}
The @ManyToOne annotation is used to create the many-to-one relationship between the Student and Address entities. The cascade option is used to cascade the required operations to the associated entity. If the cascade option is set to CascadeType.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 class is used to create the ADDRESS table.
01.package com.vaannila.student;
02. 
03.import javax.persistence.Column;
04.import javax.persistence.Entity;
05.import javax.persistence.GeneratedValue;
06.import javax.persistence.Id;
07.import javax.persistence.Table;
08. 
09.@Entity
10.@Table(name = "ADDRESS")
11.public class Address {
12. 
13.    private long addressId;
14.    private String street;
15.    private String city;
16.    private String state;
17.    private String zipcode;
18. 
19.    public Address() {
20.    }
21. 
22.    public Address(String street, String city, String state, String zipcode) {
23.        this.street = street;
24.        this.city = city;
25.        this.state = state;
26.        this.zipcode = zipcode;
27.    }
28. 
29.    @Id
30.    @GeneratedValue
31.    @Column(name = "ADDRESS_ID")
32.    public long getAddressId() {
33.        return this.addressId;
34.    }
35. 
36.    public void setAddressId(long addressId) {
37.        this.addressId = addressId;
38.    }
39.     
40.    @Column(name = "ADDRESS_STREET", nullable = false, length=250)
41.    public String getStreet() {
42.        return this.street;
43.    }
44. 
45.    public void setStreet(String street) {
46.        this.street = street;
47.    }
48. 
49.    @Column(name = "ADDRESS_CITY", nullable = false, length=50)
50.    public String getCity() {
51.        return this.city;
52.    }
53. 
54.    public void setCity(String city) {
55.        this.city = city;
56.    }
57. 
58.    @Column(name = "ADDRESS_STATE", nullable = false, length=50)
59.    public String getState() {
60.        return this.state;
61.    }
62. 
63.    public void setState(String state) {
64.        this.state = state;
65.    }
66. 
67.    @Column(name = "ADDRESS_ZIPCODE", nullable = false, length=10)
68.    public String getZipcode() {
69.        return this.zipcode;
70.    }
71. 
72.    public void setZipcode(String zipcode) {
73.        this.zipcode = zipcode;
74.    }
75. 
76.}
Now create the hibernate configuration file with the Student and Address class mapping.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<!DOCTYPE hibernate-configuration PUBLIC
03.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
05.<hibernate-configuration>
06.    <session-factory>
07.        <property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
08.        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost<;/property>
09.        <property name="hibernate.connection.username">sa</property>
10.        <property name="connection.password"></property>
11.        <property name="connection.pool_size">1</property>
12.        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
13.        <property name="show_sql">true</property>
14.        <property name="hbm2ddl.auto">create</property>
15.        <mapping class="com.vaannila.student.Student" />
16.        <mapping class="com.vaannila.student.Address" />
17.    </session-factory>
18.</hibernate-configuration>
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.            //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.
The folder structure of the example is shown below.


Hibernate Mapping One-to-One using Annotations Tutorial

  • 0
    Share
  • submit to reddit

In this example you will learn how to map one-to-one relationship using Hibernate Annotations. Consider the following relationship between Student and Address entity.

According to the relationship each student should have a unique address.
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 tables you need to create the following Java classes with hibernate annotations.
Student class is used to create the STUDENT table.
01.package com.vaannila.student;
02. 
03.import javax.persistence.CascadeType;
04.import javax.persistence.Column;
05.import javax.persistence.Entity;
06.import javax.persistence.GeneratedValue;
07.import javax.persistence.Id;
08.import javax.persistence.OneToOne;
09.import javax.persistence.Table;
10. 
11.@Entity
12.@Table(name = "STUDENT")
13.public class Student {
14. 
15.    private long studentId;
16.    private String studentName;
17.    private Address studentAddress;
18. 
19.    public Student() {
20.    }
21. 
22.    public Student(String studentName, Address studentAddress) {
23.        this.studentName = studentName;
24.        this.studentAddress = studentAddress;
25.    }
26. 
27.    @Id
28.    @GeneratedValue
29.    @Column(name = "STUDENT_ID")
30.    public long getStudentId() {
31.        return this.studentId;
32.    }
33. 
34.    public void setStudentId(long studentId) {
35.        this.studentId = studentId;
36.    }
37. 
38.    @Column(name = "STUDENT_NAME", nullable = false, length = 100)
39.    public String getStudentName() {
40.        return this.studentName;
41.    }
42. 
43.    public void setStudentName(String studentName) {
44.        this.studentName = studentName;
45.    }
46. 
47.    @OneToOne(cascade = CascadeType.ALL)
48.    public Address getStudentAddress() {
49.        return this.studentAddress;
50.    }
51. 
52.    public void setStudentAddress(Address studentAddress) {
53.        this.studentAddress = studentAddress;
54.    }
55. 
56.}
The @OneToOne annotation is used to create the one-to-one relationship between the Student and Address entities.
Address class is used to create the ADDRESS table.
01.package com.vaannila.student;
02. 
03.import javax.persistence.Column;
04.import javax.persistence.Entity;
05.import javax.persistence.GeneratedValue;
06.import javax.persistence.Id;
07.import javax.persistence.Table;
08. 
09.@Entity
10.@Table(name = "ADDRESS")
11.public class Address {
12. 
13.    private long addressId;
14.    private String street;
15.    private String city;
16.    private String state;
17.    private String zipcode;
18. 
19.    public Address() {
20.    }
21. 
22.    public Address(String street, String city, String state, String zipcode) {
23.        this.street = street;
24.        this.city = city;
25.        this.state = state;
26.        this.zipcode = zipcode;
27.    }
28. 
29.    @Id
30.    @GeneratedValue
31.    @Column(name = "ADDRESS_ID")
32.    public long getAddressId() {
33.        return this.addressId;
34.    }
35. 
36.    public void setAddressId(long addressId) {
37.        this.addressId = addressId;
38.    }
39.     
40.    @Column(name = "ADDRESS_STREET", nullable = false, length=250)
41.    public String getStreet() {
42.        return this.street;
43.    }
44. 
45.    public void setStreet(String street) {
46.        this.street = street;
47.    }
48. 
49.    @Column(name = "ADDRESS_CITY", nullable = false, length=50)
50.    public String getCity() {
51.        return this.city;
52.    }
53. 
54.    public void setCity(String city) {
55.        this.city = city;
56.    }
57. 
58.    @Column(name = "ADDRESS_STATE", nullable = false, length=50)
59.    public String getState() {
60.        return this.state;
61.    }
62. 
63.    public void setState(String state) {
64.        this.state = state;
65.    }
66. 
67.    @Column(name = "ADDRESS_ZIPCODE", nullable = false, length=10)
68.    public String getZipcode() {
69.        return this.zipcode;
70.    }
71. 
72.    public void setZipcode(String zipcode) {
73.        this.zipcode = zipcode;
74.    }
75. 
76.}
Now create the hibernate configuration file with the Student and Address class mapping.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<!DOCTYPE hibernate-configuration PUBLIC
03.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
05.<hibernate-configuration>
06.    <session-factory>
07.        <property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
08.        <property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost<;/property>
09.        <property name="hibernate.connection.username">sa</property>
10.        <property name="connection.password"></property>
11.        <property name="connection.pool_size">1</property>
12.        <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
13.        <property name="show_sql">true</property>
14.        <property name="hbm2ddl.auto">create</property>
15.        <mapping class="com.vaannila.student.Student" />
16.        <mapping class="com.vaannila.student.Address" />
17.    </session-factory>
18.</hibernate-configuration>
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 address1 = new Address("OMR Road", "Chennai", "TN", "600097");
17.            Address address2 = new Address("Ring Road", "Banglore", "Karnataka", "560000");
18.            Student student1 = new Student("Eswar", address1);
19.            Student student2 = new Student("Joe", address2);
20.            session.save(student1);
21.            session.save(student2);
22.            transaction.commit();
23.        } catch (HibernateException e) {
24.            transaction.rollback();
25.            e.printStackTrace();
26.        } finally {
27.            session.close();
28.        }
29. 
30.    }
31. 
32.}
On executing the Main class you will see the following output.
The Student table has two records.

The Address table has two record.

Each student record points to a different address record, this illustrates the one-to-one mapping.
The folder structure of the example is shown below.