Hibernate Mapping Set using XML
Last Updated :
24 Apr, 2025
In Hibernate, if we want to map one table to another with the help of a set then we use Set mapping. Set mapping can be performed if the model class or persistent class contains a set as its element. To perform set mapping, we can use a set in the mapping file. let's see how we can configure the XML mapping file for the mapping set in hibernate.
Prerequisites
- Hibernate: Hibernate is a Java framework that provides various functionalities for implementing ORM in Java.
- Maven: Maven is a build tool used for enterprise Java applications.
- MySQL: MySQL is a relational database management system that we will be using for storing our data.
Mapping Set Using XML
- To map set using XML. First, the persistent class in hibernate should contain a set element.
- The set element should have getter and setter in the class.
- To Configure mapping, we have to set attribute in XML file in below format.
<set name="Attribute Name" table="Table Name">
<key column="Key-Column-Name"></key>
<element column="Element Name" type="Element Type"></element>
</set>
Example of Hibernate Mapping Set
- Initialize a Maven project in Eclipse. Add the class where we will put our main logic.
- Now we will add persistent class in the project. Here we have created a persistent class Todo.java as below.
Todo.java:
Java
package com.gfg.example;
import java.util.Set;
public class Todo {
private Integer taskid;
private String taskName;
private String task;
private Set<String> allocations;
public Set<String> getAllocations() {
return allocations;
}
public void setAllocations(Set<String> allocations) {
this.allocations = allocations;
}
public Todo() {
}
public Todo(Integer taskid, String taskName, String task) {
super();
this.taskid = taskid;
this.taskName = taskName;
this.task = task;
}
public Integer getTaskid() {
return taskid;
}
public void setTaskid(Integer taskid) {
this.taskid = taskid;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
}
As we can see we have Set element as a part of persistent class which is Allocations.
Now let's add XML configuration file hibernate as below. We have created a database hb which contains tables for Todo and Todoa for storing Todo and Allocations respectively. (Hibernate.cfg.xml)
XML
<?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://127.0.0.1/hb</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">msroot</property>
</session-factory>
</hibernate-configuration>
Now let's add mapping file for our persistent class. We should also map set in this file as described above.The file will look like below. (Todo.hbm.xml)
XML
<?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>
<class name="com.gfg.example.Todo" table="TODO">
<id name="taskid" type="java.lang.Integer">
<column name="TASKID" />
<generator class="assigned" />
</id>
<property name="taskName" type="java.lang.String">
<column name="TASKNAME" />
</property>
<property name="task" type="java.lang.String">
<column name="TASK" />
</property>
<set name="allocations" table="TODOA">
<key column="aid"></key>
<element column="name" type="string"></element>
</set>
</class>
</hibernate-mapping>
Both of the above xml files should be present in resources folder of application.
Finally let's add logic in our main class to test the application. We will create two methods to insert and fetch the data in Todo. The file will contain following code. (HibernateTest.java)
Java
package com.gfg.example;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.TypedQuery;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateTest {
private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
Configuration config = new Configuration();
config.configure();
config.addAnnotatedClass(Todo.class);
config.addResource("Todo.hbm.xml");
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
factory = config.buildSessionFactory(serviceRegistry);
HibernateTest hbTest = new HibernateTest();
HashSet<String> a1 = new HashSet<String>();
a1.add("gfg1");
a1.add("gfg2");
HashSet<String> a2 = new HashSet<String>();
a2.add("gfg3");
a2.add("gfg4");
hbTest.insertTodo(1, "Health", "Do Workout", a1);
hbTest.insertTodo(2, "Learning", "Solve Code", a2);
hbTest.fetchTodo();
}
private long insertTodo(int id, String taskname, String task, Set<String> s) {
Session session = factory.openSession();
Transaction tx = null;
Integer TodoS = null;
try {
tx = session.beginTransaction();
Todo e = new Todo();
e.setTaskid(id);
e.setTaskName(taskname);
e.setTask(task);
e.setAllocations(s);
TodoS = (Integer) session.save(e);
tx.commit();
} catch (HibernateException ex) {
if (tx != null)
tx.rollback();
ex.printStackTrace();
} finally {
session.close();
}
return TodoS;
}
private void fetchTodo() {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query query = session.createQuery("from Todo");
List<Todo> list = query.list();
Iterator<Todo> itr = list.iterator();
while (itr.hasNext()) {
Todo q = itr.next();
System.out.println("Task Name: " + q.getTaskName());
System.out.println("Task : " + q.getTask());
System.out.println("Allocations : ");
Set<String> set = q.getAllocations();
Iterator<String> itr2 = set.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
} catch (HibernateException ex) {
if (tx != null)
tx.rollback();
ex.printStackTrace();
} finally {
session.close();
}
}
}
Output:
.png)
In the above code we have inserted two records in Todo each having Set element that contains 2 elements each. Finally let's run this application. To run the application, build the maven project to generate package. Then run it as java project.
Conclusion
So, that is how we perform set mapping in hibernate. We have seen example to perform Set mapping in hibernate using XML. Also, we have learned about format of mapping set in file. This hibernate functionality can be used to implement more complex mappings in database.
Similar Reads
Hibernate - SortedSet Mapping
SortedSet can be viewed in a group of elements and they do not have a duplicate element and ascending order is maintained in its elements. By using <set> elements we can use them and the entity should have a Sortedset of values. As an example, we can have a freelancer who works for multiple co
6 min read
Hibernate - SortedMap Mapping
SortedMap is a map that always maintains its corresponding entries in ascending key order. In Hibernate, using the <map> element and 'sort' as 'natural' we can maintain the SortedMap. Let us see that by using the one-to-many relationship concept. For example, for a programming language like Ja
6 min read
Hibernate - Types of Mapping
Hibernate is a Java framework that simplifies the development of Java applications to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. There are different r
2 min read
Hibernate - One-to-Many Mapping
Hibernate is used to increase the data manipulation efficiency between the spring application and the database, insertion will be done is already defined with the help of hibernating. JPA (Java persistence API) is like an interface and hibernate is the implementation of the methods of the interface.
5 min read
Hibernate - Many-to-One Mapping
Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and wi
5 min read
Hibernate - Map Mapping
In a java collection, a map stores elements in key-value pairs. It will not allow duplicate elements. The map interface allows the mapped contents as a set of keys(keys alone) and a collection of values(values alone) or a set of key-value mappings. java.util.HashMap will be useful to initialize an u
10 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question
4 min read
Hibernate - Mapping List
In Hibernate, in order to go for an ordered collection of items, mostly List is the preferred one, Along with List, we have different collection mapping like Bag, Set, Map, SortedSet, SortedMap, etc., But still in many places mapping list is the most preferred way as it has the index element and hen
3 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In thi
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time
6 min read