VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/hibernate-mapping-set-using-xml/

⇱ Hibernate Mapping Set using XML - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hibernate Mapping Set using XML

Last Updated : 23 Jul, 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:

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)

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)

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)

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.

Comment

Explore