< Prev
Next >



Hibernate Mapping Sorted Set - TreeSet



Today we are going to understand how to persist a collection object based on a sorted set(TreeSet) collection within the database using Hibernate. By default, a TreeSet stores the collection of elements in an ascending order hence the collection of elements will be stored in an ascending order within the database.




Why do we have to add a collection object in an Entity class.


Let's suppose we have a class Companies containing the information such as - id, name and a Set collection of String object(representing names of all the employees of a particular company).
That's why we are going to need a collection object in Companies class, representing multiple employee names in a company.

Let's put this example to work and make it easier for you to understand the whole concept.




Note :







Creating a POJO/Entity class


We are creating a simple Java Entity class whose objects(containing the TreeSet collection object) needs to be persisted/saved, these objects are also known as Plain Old Java Objects(POJO). The objects of an Entity class are also known as an Entity objects.

This collection object is stored in a separate table, while the Entity object is stored in a separate table in the database. Some may even refer to this Entity class as the Model class.

This Entity class will implement the Comparator interface to sort the collection of elements in a descending order. By default, a TreeSet stores the collection of elements in an ascending order.


Companies.java
package decodejava;

import java.util.Set;
import java.util.TreeSet;

public class Companies 
{
	private int id;
	private String companyName;
	private Set<String> employeeNames = new TreeSet<String>();



	public int getId() 
	{
		return id;
	}



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



	public String getCompanyName() 
	{
		return companyName;
	}



	public void setCompanyName(String companyName) 
	{
		this.companyName = companyName;
	}



	public Set<String> getEmployeeNames() 
	{
		return employeeNames;
	}



	public void setEmployeeNames(Set<String> employeeNames) 
	{
		this.employeeNames = employeeNames;
	}

}





Creating the class that calls the Hibernate API - Utility class


This class will create an objects of Companies Entity class , which will be persisted using the Hibernate API and an object-relational mapping(ORM) in the database is performed.

The Hiber class creates a Configuration object, used to configure the Hibernate. This is the first object we use when using the Hibernate. This object is used to specify the location of a configuration file and mapping document used by Hibernate. Using Configuration object we can create a SessionFactory object, which is eventually used to create a Session object to perform the object persistence operations.


Hiber.java
package decodejava;

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

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


public class Hiber
{
	
	public static void main(String... ar)
	{
	Configuration config = new Configuration();
	SessionFactory sf = config.configure().buildSessionFactory();
	Session session  = sf.openSession();
	
	
	//Creating the first Company
	Companies company1 = new Companies();
	company1.setCompanyName("Company1");
	
	
	
	//Creating the second Company
	Companies company2 = new Companies();
	company2.setCompanyName("Company2");
	

	
	//Creating a set collection of employees of the first company
	TreeSet<String> collection1 = new TreeSet<String>(new Companies());
	collection1.add("Hugh Grant");
	collection1.add("Anuj Sobti");
	collection1.add("James Stewart");
	
	//Setting the collection of the employees to the first company
	company1.setEmployeeNames(collection1);
	
	
	
	//Creating a set collection of employees of the second company
	TreeSet<String> collection2 = new TreeSet<String>(new Companies());
	collection2.add("Rakesh Khanna");
	collection2.add("Sean Webber");
	collection2.add("Adam Shot");
	
	//Setting the set collection of the employees to the second company
	company2.setEmployeeNames(collection2);
 
	

	session.beginTransaction();
	session.save(company1);  
	session.save(company2);
	session.getTransaction().commit();
	session.close();						          		
	
	
	
	//Creating a new Session to retrieve the objects.
	session= sf.openSession();
	session.beginTransaction();
	company1 = (Companies)session.get(Companies.class,1);
	company2 = (Companies)session.get(Companies.class,2);

	System.out.println("Retrieving the saved objects");
	System.out.println("Name of the first company : "+ company1.getCompanyName());
	Set<String> employeeNames1 = company1.getEmployeeNames();
	System.out.println(employeeNames1);
    
    
	System.out.println("Retrieving the saved objects");
	System.out.println("Name of the second company : "+ company2.getCompanyName());
	Set<String> employeeNames2 = company2.getEmployeeNames();
	System.out.println(employeeNames2);
	session.getTransaction().commit();
	session.close();
	}
}





Adding JARs







Adding the mapping-resource file




This mapping document tells Hibernate -


employeedetails.hbm.xml
<?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 = "decodejava.Companies" table = "COMPANIES">
      
      <id name = "id"  column = "Company_ID" type = "int">
         
    
      <property name = "companyName" column = "Company_Name" type = "string"/>
      
	 
	   <set name ="employeeNames" table="COMPANY_EMPLOYEES" cascade="all" order-by="Employee_Names">
	  	<key column="Company_ID"/>
	  	<element column="Employee_Names" type="string"/>
	  </set>
     
	  
	  
    </class>
	
</hibernate-mapping>


This mapping document has <hibernate-mapping> as the root element and its child element <class>, containing all the class elements.













Note :


If we don't use order-by attribute within the set element in our mapping resource file, the retrieved collection of employee names of a company will not be in any order, despite using the TreeSet to store them, because Hibernate uses the functionality of Set interface when a set of any kind(sorted - TreeSet or unsorted - HashSet)is pulled out of database.




Adding a configuration file


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



<hibernate-configuration>

<session-factory>


<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>


<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>


<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>


<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
        
        
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>


<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>


<!--Naming the mapping resource file -->
<mapping resource ="companies.hbm.xml"/>

</session-factory>

</hibernate-configuration>





Directory Structure of Hibernate Project




The picture above depicts how and where to arrange POJO/Entity(.java) file and the other the class(that calls the hibernate into action) in a specific directory structure.

Project Folder - MappingTreeSetWithXML is the name of our Project and it is a top-level directory.






Execution


Finally, after executing Hiber class, two separate tables will be created in the database -
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2