Hibernate – many-to-one relationship example

hibernate_logo
Well, many-to-one is the type of relationship in Hibernate. This is child to parent relationship where many child can belongs to one parent. Here, you have to establishe relationship between two different entity/domain model class.

I have tested this program code using with:
– JDK 7
– MySQL 5.5
– Eclipse IDE
– Hibernate 3

For library/.jar dependecy you can download source code which is mention at the last of our post hello world program in Hibernate. And for simplicity, I kept all the files under one package for example: com.mysoftkey.relationship.many2one . At the end of this post you will learn, how to establish relationship of many-to-one in Hibenate using .hbm.xml files.

1. What is many-to-one Relationship

This is many to one relationship example, for simplicity I keep all the classes in one package i.e. com.mysoftkey.relationship.many2one and then tested the code in Eclise IDE, JDK 6, MySQL 5.5.

Here, you can say many student can have one addresses. in this example many child (student entity) can have one parent ( i.e. Address entity).

In this example you will learn how to map many-to-one relationship using Hibernate. 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 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.

2. POJO/domain model classes for many-to-one relationship

File: com/mysoftkey/relationship/many2one/Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.mysoftkey.relationship.many2one;
 
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
 
public class Student implements Serializable {
 
  private long studentId;
  private String StudentName;
  private Address studentAddress;
 
  public Student() {
  }
 
  public Student(String StudentName, Address studentAddress) {
    this.StudentName = StudentName;
    this.studentAddress = studentAddress;
  }
 
// Generate setter/gettetr methods, this is required
// omitted to short and clear the code
 
}

File: com/mysoftkey/relationship/many2one/Address.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.mysoftkey.relationship.many2one;
 
import java.io.Serializable;
 
public class Address implements Serializable {
 
  private long addressId;
  private String street;
  private String city;
  private String state;
  private String zipcode;
 
  public Address() {
  }
 
  public Address(String street, String city, String state, String zipcode) {
    this.street = street;
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
  }
 
  // Generate setter/gettetr methods, this is required
  // omitted to short and clear the code}

3. mapping for many to one relationship

File: com/mysoftkey/relationship/many2one/Student.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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 auto-import="false"	package="com.mysoftkey.relationship.many2one">
  <class name="Student" table="STUDENT_many2one">
    <id name="studentId" type="long">
       <column name="STUDENT_ID" />
       <generator class="increment" />
    </id>
    <property name="StudentName" type="java.lang.String">
	<column name="STUDENT_NAME" />
    </property>
 
    <many-to-one name="studentAddress" class="Address" column="STUDENT_ADDRESS"
		cascade="all" not-null="true" />
  </class>
</hibernate-mapping>

File: com/mysoftkey/relationship/many2one/Address.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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 auto-import="false" package="com.mysoftkey.relationship.many2one">
  <class name="Address" table="address_many2one">
	<id name="addressId" type="long">
		<column name="ADDRESS_ID" />
		<generator class="increment" />
	</id>
	<property name="street" type="java.lang.String">
		<column name="ADDRESS_STREET" />
	</property>
	<property name="city" type="java.lang.String">
		<column name="ADDRESS_CITY" />
	</property>
	<property name="state" type="java.lang.String">
		<column name="ADDRESS_STATE" />
	</property>
	<property name="zipcode" type="java.lang.String" column="ADDRESS_ZIPCODE" />
 
 </class>
</hibernate-mapping>

4. Hibernate Configuration

This file is Hbirnate configuration file, keep this in application root folder.

File: hibernate.cfg.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
   <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_example</property>
   <property name="hibernate.connection.username">root</property>
   <property name="connection.password">root</property>
   <property name="connection.pool_size">2</property>
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   <property name="show_sql">true</property>
   <property name="hbm2ddl.auto">create</property>
 
    <!-- ManyToOne relationship , and increment Generator class as well -->
    <mapping resource="com/delhiguru/relationship/many2one/Student.hbm.xml"/>
    <mapping resource="com/delhiguru/relationship/many2one/Address.hbm.xml"/>
 
  </session-factory>
</hibernate-configuration>

5. Run Client of Many to one relationship

File: com/mysoftkey/relationship/many2one/MainManyToOneClient.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.mysoftkey.relationship.many2one;
 
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
 
public class MainManyToOneClient {
 
  /**
   * @param args
   */
  /*
   * Hibernate Mapping Many-to-One
   * 
   * In this example you will learn how to map many-to-one relationship using
   * Hibernate. Consider the following relationship between Student and Address
   * entity. According to the relationship many students can have the same
   * address.
   * 
   */
  public static void main(String[] args) {
 
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      Address address = new Address("Dwarka", "New Delhi", "ND", "110045");
      // By using cascade=all option the address need not be saved explicitly
      // when the student object is persisted the address
      // will be automatically saved.
      // session.save(address);
      Student student1 = new Student("Ashish", address);
      Student student2 = new Student("Ranjeet", address);
      session.save(student1);
      session.save(student2);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
 
  }
 
}

6. Output of many to one hibernate relationship

Eclipse console output:

1
2
3
4
5
Hibernate: select max(STUDENT_ID) from STUDENT_many2one
Hibernate: select max(ADDRESS_ID) from address_many2one
Hibernate: insert into address_many2one (ADDRESS_STREET, ADDRESS_CITY, ADDRESS_STATE, ADDRESS_ZIPCODE, ADDRESS_ID) values (?, ?, ?, ?, ?)
Hibernate: insert into STUDENT_many2one (STUDENT_NAME, STUDENT_ADDRESS, STUDENT_ID) values (?, ?, ?)
Hibernate: insert into STUDENT_many2one (STUDENT_NAME, STUDENT_ADDRESS, STUDENT_ID) values (?, ?, ?)

mySQL terminal output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mysql> SELECT * FROM address_many2one;
+------------+----------------+--------------+---------------+-----------------+
| ADDRESS_ID | ADDRESS_STREET | ADDRESS_CITY | ADDRESS_STATE | ADDRESS_ZIPCODE |
+------------+----------------+--------------+---------------+-----------------+
|          1 | Dwarka         | NEW Delhi    | ND            | 110045          |
+------------+----------------+--------------+---------------+-----------------+
1 ROW IN SET (0.00 sec)
 
mysql> SELECT * FROM STUDENT_many2one;
+------------+--------------+-----------------+
| STUDENT_ID | STUDENT_NAME | STUDENT_ADDRESS |
+------------+--------------+-----------------+
|          1 | Ashish       |               1 |
|          2 | Ranjeet      |               1 |
+------------+--------------+-----------------+
2 ROWS IN SET (0.00 sec)
 
mysql>

Your comments are welcome to improve this many-to-one relationship in Hibernate. Happy Learning :)

Please follow and like us:
RSS
Follow by Email
Facebook
LinkedIn
Google+

Leave a Reply

Your email address will not be published. Required fields are marked *