Open In App

Hibernate Mapping Set using XML

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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"
<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"
  
<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:

Output of test class

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads