![]() |
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
Mapping Set Using XML
<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
Todo.java: 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) 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) 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) Java
Output: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. ConclusionSo, 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. |
Reffered: https://www.geeksforgeeks.org
Advance Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |