How to Map Collection in Hibernate?

In the previous article, we have seen What is Mapping file in Hibernate Framework. you can check it here What is Hibernate Mapping file?. In this article, we will see How to Map collection objects in Hibernate.

In Java, we have a concept called Collection which is a group of objects defined in a single unit. We will see How is mapping of Collection in Hibernate Framework.

Mapping of Collection in Hibernate

We need to Map Collection in Persistence class. We have some types of Collection Type that we use in an application such as

  • java.util.Set
  • java.util.SortedSet
  • java.util.List
  • java.util.Map
  • java.util.SortedMap
  • java.util.Collection

Let’s discuss some of them in detail

How to Map Set Interface?

A Set Interface is an interface that extends the Collection Interface and is present in java.util package.

  • When we want to store objects in the order we use Set Interface.
  • It doesn’t allow duplicate values
  • In the Hibernate framework, a Set is mapped with<set> element.

Example of Mapping Set Interface

Let’s create a simple example where we will use the SET interface and we will learn how to map Collection in Mapping file.

Create a database and table

<--------Create Database--------->
mysql>create database student;
<-------Use databse--------------> 
mysql>use student;
<-------Create Table student_table------------->
mysql>CREATE TABLE `student_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `fname` varchar(45) DEFAULT NULL,
  `lname` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;
<--------Create child table degree_table--------->
mysql>CREATE TABLE `degree_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `sid` int DEFAULT NULL,
  `dname` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `sid` (`sid`),
  CONSTRAINT `degree_table_ibfk_1` FOREIGN KEY (`sid`) REFERENCES `student_table` (`id`)
)

Create a persistence class-Student.java

import java.util.HashSet;
import java.util.Set;

public class Student {

  private int id;
  private String fname;
  private String lname;
  private Set degrees;

  public Student(String fname, String lname) {
    super();
    this.fname = fname;
    this.lname = lname;

  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFname() {
    return fname;
  }

  public void setFname(String fname) {
    this.fname = fname;
  }

  public String getLname() {
    return lname;
  }

  public void setLname(String lname) {
    this.lname = lname;
  }

  public Set getDegrees() {
    return degrees;
  }

  public void setDegrees(Set degree) {
    this.degrees = degree;
  }

}

Degree.java

public class Degree {

  private int id;
  private String dname;

  public Degree(String dname) {

    this.dname = dname;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getDname() {
    return dname;
  }

  public void setDname(String dname) {
    this.dname = dname;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((dname == null) ? 0 : dname.hashCode());
    result = prime * result + id;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Degree other = (Degree) obj;
    if (dname == null) {
      if (other.dname != null)
        return false;
    } else if (!dname.equals(other.dname))
      return false;
    if (id != other.id)
      return false;
    return true;
  }

}

hibernate.cfg.xml file

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>

  <session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/student</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping resource="Student.hbm.xml" />
  </session-factory>

</hibernate-configuration>

Mapping File-Student.hbm.xml

  • In this file, <hibernate-mapping> is the root element.
  • To map the Student.java and Degree.java we have <class> element.
  • The <set> element here is for the relationship between Student and Degree class.
  • <key> element shows the foreign key for the degree table.
  • <onetomany> element shows the mapping between one to many like one Student can have many degrees.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="Student" table="student_table">


    <id name="id" type="int" column="id">
      <generator class="native" />
    </id>
    <property name="fname" column="fname" type="string" />
    <property name="lname" column="lname" type="string" />

    <set name="degrees" cascade="all">
      <key column="sid" />
      <one-to-many class="Degree" />
    </set>

  </class>

  <class name="Degree" table="degree_table">


    <id name="id" type="int" column="id">
      <generator class="native" />
    </id>

    <property name="dname" column="dname" type="string" />

  </class>

</hibernate-mapping>

TestClass.java

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestClass {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    HashSet set = new HashSet<>();
    set.add(new Degree("BE"));
    set.add(new Degree("ME"));
    set.add(new Degree("PHD"));
    // Student student=new Student(1,"Nicolas","Dsouza",set);
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    Student student2 = new Student("Nicoals", "Dsouza");
    student2.setDegrees(set);
    session.save(student2);
    System.out.println("added");
    session.getTransaction().commit();
  }

}

Output:

mysql> select * from student_table;
+----+---------+--------+
| id | fname   | lname  |
+----+---------+--------+
| 17 | Nicoals | Dsouza |
+----+---------+--------+
2 rows in set (0.00 sec)

mysql> select * from degree_table;
+----+------+-------+
| id | sid  | dname |
+----+------+-------+
| 12 |   17 | PHD   |
| 13 |   17 | ME    |
| 14 |   17 | BE    |
+----+------+-------+
6 rows in set (0.00 sec)

How to Map List Interface in Hibernate?

List Interface is an interface that extends Collection Interface which is present in java.util package.

  • List Interface stores the element in an unordered collection.
  • It allows duplicate values.
  • If our persistent class has a list object in the Hibernate framework we can map using the <list> element.

Example of Mapping List Interface

Let’s create a simple example where we will use the List interface and we will learn how to map List Collection in Mapping file.

Create a database and table

<-------create database--------->
mysql>create database garden;
<--------use garden database---->
mysql>use garden;
<--------create Table garden_table---->
mysql>CREATE TABLE `garden_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `gname` varchar(45) DEFAULT NULL,
  `gcity` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
<------create child table flower_table--->
mysql>CREATE TABLE `flower_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `fname` varchar(45) DEFAULT NULL,
  `gid` int DEFAULT NULL,
  `indexid` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `gid` (`gid`),
  CONSTRAINT `flower_table_ibfk_1` FOREIGN KEY (`gid`) REFERENCES `garden_table` (`id`)
) ;

Create a persistent class-Garden.java

import java.util.List;

public class Garden {

  private int id;
  private String gardenName;
  private String gardenCity;
  private List flowers;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getGardenName() {
    return gardenName;
  }

  public void setGardenName(String gardenName) {
    this.gardenName = gardenName;
  }

  public String getGardenCity() {
    return gardenCity;
  }

  public void setGardenCity(String gardenCity) {
    this.gardenCity = gardenCity;
  }

  public List getFlowers() {
    return flowers;
  }

  public void setFlowers(List flowers) {
    this.flowers = flowers;
  }

  public Garden(String gardenName, String gardenCity) {
    super();
    this.gardenName = gardenName;
    this.gardenCity = gardenCity;
  }

  public Garden() {

  }

}

Flower.java

public class Flower {

  private int id;
  private String fname;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFname() {
    return fname;
  }

  public void setFname(String fname) {
    this.fname = fname;
  }

  public Flower(String fname) {
    super();
    this.fname = fname;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((fname == null) ? 0 : fname.hashCode());
    result = prime * result + id;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Flower other = (Flower) obj;
    if (fname == null) {
      if (other.fname != null)
        return false;
    } else if (!fname.equals(other.fname))
      return false;
    if (id != other.id)
      return false;
    return true;
  }

  public Flower() {

  }
}

hibernate.cfg.xml file

 
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

  <session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/garden</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping resource="Garden.hbm.xml" />
  </session-factory>

</hibernate-configuration>

Mapping file-Garden.hbm.xml

  • In this file, <hibernate-mapping> is the root element.
  • To map the Garden.java and Flower.java we have <class> element.
  • The <set> element here is for the relationship between Garden and Flower class.
  • <key> element shows the foreign key for the flower_table.
  • <onetomany> element shows the mapping between one to many like one Student can have many degrees.
  • In this one more element <list-index> is included to keep the position of the element. This index value starts from 0.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="Garden" table="garden_table">


    <id name="id" type="int" column="id">
      <generator class="native" />
    </id>
    <property name="gardenName" column="gname" type="string" />
    <property name="gardenCity" column="gcity" type="string" />

    <list name="flowers" cascade="all">
      <key column="gid" />
      <list-index column="indexid" />
      <one-to-many class="Flower" />
    </list>

  </class>

  <class name="Flower" table="flower_table">


    <id name="id" type="int" column="id">
      <generator class="native" />
    </id>

    <property name="fname" column="fname" type="string" />

  </class>

</hibernate-mapping>

TestClass.java

import java.util.ArrayList;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestClass {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    ArrayList arrayList = new ArrayList<Flower>();
    arrayList.add(new Flower("Lily"));
    arrayList.add(new Flower("Tulips"));
    arrayList.add(new Flower("Orchids"));
    arrayList.add(new Flower("Sunflowers"));
    arrayList.add(new Flower("Lavender"));
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    Garden garden = new Garden("KingNursery", "Mumbai");
    garden.setFlowers(arrayList);
    session.save(garden);
    System.out.println("added");
    session.getTransaction().commit();

  }

}

Output

mysql> select * from garden_table;
+----+-------------+--------+
| id | gname       | gcity  |
+----+-------------+--------+
|  2 | KingNursery | Mumbai |
+----+-------------+--------+
1 row in set (0.12 sec)

mysql> select * from flower_table;
+----+------------+------+---------+
| id | fname      | gid  | indexid |
+----+------------+------+---------+
|  1 | Lily       |    2 |       0 |
|  2 | Tulips     |    2 |       1 |
|  3 | Orchids    |    2 |       2 |
|  4 | Sunflowers |    2 |       3 |
|  5 | Lavender   |    2 |       4 |
+----+------------+------+---------+
5 rows in set (0.20 sec)

How to Map Collection Bag in Hibernate?

A Bag is an interface in Collection which is a collection of objects and is present in java.util.Collection package.

  • It contains an unordered collection of objects.
  • It contains the duplicate element.
  • If our persistent class has a Bag object in the Hibernate framework we can map using the <Bag> element.

Note: Example of Bag Interface will be the same as that of List Example only difference in the Mapping file we will use <bag> element.

How to map Map Interface in Hibernate?

A  Map is the Interface of Collection Framework which is present in java.util package.

  • It stores the element in key-value pairs.
  • It uses index-based collections. (index column is for key and element column is for value)
  • In Hibernate to map Map Interface, we use the <map> element.

Example of Mapping Map Interface

Let’s create a simple example where we will use the Map interface and we will learn how to map Map Collection in Mapping file.

Create a database and table

<------Create database------->
mysql>create database college
<------Use database---------->
mysql>use college;
<-----create table college_table--->
mysql>CREATE TABLE `college_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `cname` varchar(45) DEFAULT NULL,
  `cloc` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;
<-----create child table student---->
mysql>CREATE TABLE `student_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `sname` varchar(45) DEFAULT NULL,
  `sbranch` varchar(45) DEFAULT NULL,
  `cid` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `cid` (`cid`),
  CONSTRAINT `student_table_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `college_table` (`id`)
) ;

Create a persistence class-College.java

import java.util.Map;

public class College {

  private int id;
  private String college_name;
  private String college_loc;
  private Map students;

  public College(String college_name, String college_loc) {
    super();
    this.college_name = college_name;
    this.college_loc = college_loc;
  }

  public College() {
    super();
    // TODO Auto-generated constructor stub
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getCollege_name() {
    return college_name;
  }

  public void setCollege_name(String college_name) {
    this.college_name = college_name;
  }

  public String getCollege_loc() {
    return college_loc;
  }

  public void setCollege_loc(String college_loc) {
    this.college_loc = college_loc;
  }

  public Map getStudents() {
    return students;
  }

  public void setStudents(Map students) {
    this.students = students;
  }

}

Student.java

public class Student {

  private int id;
  private String student_branch;

  public Student(String student_branch) {
    super();

    this.student_branch = student_branch;
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getStudent_branch() {
    return student_branch;
  }

  public void setStudent_branch(String student_branch) {
    this.student_branch = student_branch;
  }

  public Student() {
    super();
    // TODO Auto-generated constructor stub
  }

}

hibernate.cfg.xml file

<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
          <hibernate-configuration>
  <session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/college</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping resource="College.hbm.xml" />
  </session-factory>
</hibernate-configuration>

Mapping file-College.hbm.xml

  • In this file, <hibernate-mapping> is the root element.
  • To map the College.java and Student.java we have <class> element.
  • The <map> element here is for the relationship between College and Student class.
  • <key> element shows the foreign key for the student_table.
  • <onetomany> element shows the mapping between one to many like one College can have many branches.
  • In this one more element <index> is included for the key (in this we have student_name as key)
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="College" table="college_table">
    <id name="id" column="id" type="int">
      <generator class="native" />
    </id>
    <map name="students" cascade="all">
      <key column="cid" />
      <index column="sname" type="string" />
      <one-to-many class="Student" />
    </map>
    <property name="college_name" column="cname" type="string" />
    <property name="college_loc" column="cloc" type="string" />
  </class>
  <class name="Student" table="student_table">
    <id name="id" type="int" column="id">
      <generator class="native" />
    </id>
    <property name="student_branch" type="string" column="sbranch" />
  </class>
</hibernate-mapping>

TestClass.java

import java.util.HashMap;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestClass {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    HashMap map = new HashMap<>();
    map.put("Rahul", new Student("CSE"));
    map.put("Saurav", new Student("E&C"));
    map.put("Sachin", new Student("Mech"));
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    College college = new College("ABC", "London");
    college.setStudents(map);
    session.save(college);
    System.out.println("added");
    session.getTransaction().commit();

  }

}

Output

mysql> select * from college_table;
+----+-------+--------+
| id | cname | cloc   |
+----+-------+--------+
|  1 | ABC   | London |
+----+-------+--------+
1 row in set (0.02 sec)

mysql> select * from student_table;
+----+--------+---------+------+
| id | sname  | sbranch | cid  |
+----+--------+---------+------+
|  1 | Saurav | E&C     |    1 |
|  2 | Rahul  | CSE     |    1 |
|  3 | Sachin | Mech    |    1 |
+----+--------+---------+------+
3 rows in set (0.02 sec)

Thus, We have learned how to map collection in the Hibernate mapping file.

In the next article of this tutorial, we will cover what is Association mapping in Hibernate Framework.