Hibernate @SortComparator and @SortNatural Example for SortedSet Mapping

By Arvind Rai, February 07, 2016
On this page we will provide hibernate @SortComparator and @SortNatural example for SortedSet mapping. These annotation has been introduced in hibernate 4.3 deprecating @Sort annotation. @SortComparator specifies comparator class which implements Comparator interface and @SortNatural uses sorting with Comparable interface implemented by entity. @SortComparator and @SortNatural performs in-memory sorting for Set and Map. Their functions are different from @OrderBy because it is applied during SQL SELECT. Here we will provide complete example for @SortComparator and @SortNatural annotations.

Software Used

We are using following software and tools in our demo.
1. Java 8
2. Hibernate 4.3
3. Gradle
4. Eclipse
5. MySQL

Table Data used in Demo

Find the data for book table.
Hibernate 4 @SortComparator and @SortNatural Example for SortedSet Mapping
Find the data for student table.
Hibernate 4 @SortComparator and @SortNatural Example for SortedSet Mapping

Gradle File

Find the gradle file to resolve the JAR dependencies.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'hibernate'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.hibernate:hibernate-core:4.3.11.Final'
    compile 'mysql:mysql-connector-java:5.1.31'
}   

SortedSet Mapping with @SortComparator

@SortComparator is used to specify java Comparator to sort the Set and Map. Find the code snippet for how to use.
	@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	@JoinColumn(name="std_id")
	@SortComparator(BookNameComparator.class)
	private SortedSet<Book> books;
	public int getStdId() {
		return stdId;
	} 
Find the example.
Book.java
package com.concretepage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name ="book")
public class Book {
	@Id
	@Column(name ="book_id")
	private int bookId;
	@Column(name = "book_name")
	private String bookName;
	@Column(name = "writer")	
	private String writer;
	public int getBookId() {
		return bookId;
	}
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
} 
BookNameComparator.java
package com.concretepage;
import java.util.Comparator;
public class BookNameComparator implements Comparator<Book> {
    @Override
    public int compare(Book b1, Book b2) {
      return b1.getBookName().compareTo(b2.getBookName());
    }
} 
Student.java
package com.concretepage;
import java.util.SortedSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SortComparator;
@Entity
@Table(name = "student")
public class Student {
	@Id
	@Column(name = "std_id")
	private int stdId;
	@Column(name = "std_name")
	private String stdName;
	@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	@JoinColumn(name="std_id")
	@SortComparator(BookNameComparator.class)
	private SortedSet<Book> books;
	public int getStdId() {
		return stdId;
	}
	public void setStdId(int stdId) {
		this.stdId = stdId;
	}
	public String getStdName() {
		return stdName;
	}
	public void setStdName(String stdName) {
		this.stdName = stdName;
	}
	public SortedSet<Book> getBooks() {
		return books;
	}
	public void setBooks(SortedSet<Book> books) {
		this.books = books;
	}
} 
hibernate.cfg.xml
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/concretepage</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="com.concretepage.Book"/>          
    <mapping class="com.concretepage.Student"/>
   </session-factory>
</hibernate-configuration> 
 
HibernateUtil.java
package com.concretepage;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
     private static SessionFactory sessionFactory ;
     static {
    	   Configuration configuration = new Configuration().configure();
    	   StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    			applySettings(configuration.getProperties());
           sessionFactory = configuration.buildSessionFactory(builder.build());
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void closeSessionFactory() {
    	sessionFactory.close();
    }
} 
HibernateDemo.java
package com.concretepage;
import org.hibernate.Session;
public class HibernateDemo {
  public static void main(String[] args) {
	 Session session = HibernateUtil.getSessionFactory().openSession();
	 Student student = (Student) session.get(Student.class, new Integer(1));
	 for (Book book: student.getBooks()) {
		 System.out.println(book.getBookName());
	 }
	 session.close();
	 HibernateUtil.closeSessionFactory();
  }
} 
Find the output.
Hibernate: select student0_.std_id as std_id1_1_0_, student0_.std_name as std_name2_1_0_, books1_.std_id as std_id4_1_1_, books1_.book_id as book_id1_0_1_, books1_.book_id as book_id1_0_2_, books1_.book_name as book_nam2_0_2_, books1_.writer as writer3_0_2_ from student student0_ left outer join book books1_ on student0_.std_id=books1_.std_id where student0_.std_id=?
Mahabharat
Nirmla
Ramayan 

SortedSet Mapping with @SortNatural

@SortNatural annotation uses Comparable to sort the data. The entity implements Comparable interface. For the code snippet.
	@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	@JoinColumn(name="std_id")
	@SortNatural
	private SortedSet books;
	public int getStdId() {
		return stdId;
	} 
Find the example.
Book.java
package com.concretepage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name ="book")
public class Book implements Comparable<Book> {
	@Id
	@Column(name ="book_id")
	private int bookId;
	@Column(name = "book_name")
	private String bookName;
	@Column(name = "writer")	
	private String writer;
	@Override
	public int compareTo(Book o) {
		return writer.compareTo(o.getWriter());
	}
	//setter getter
} 
Student.java
package com.concretepage;
import java.util.SortedSet;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.SortNatural;
@Entity
@Table(name = "student")
public class Student {
	@Id
	@Column(name = "std_id")
	private int stdId;
	@Column(name = "std_name")
	private String stdName;
	@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
	@JoinColumn(name="std_id")
	@SortNatural
	private SortedSet<Book> books;
	//setter getter
}	
Replace the line in HibernateDemo class by following.
	 for (Book book: student.getBooks()) {
		 System.out.println(book.getWriter());
	 } 
Find the output.
Hibernate: select student0_.std_id as std_id1_1_0_, student0_.std_name as std_name2_1_0_, books1_.std_id as std_id4_1_1_, books1_.book_id as book_id1_0_1_, books1_.book_id as book_id1_0_2_, books1_.book_name as book_nam2_0_2_, books1_.writer as writer3_0_2_ from student student0_ left outer join book books1_ on student0_.std_id=books1_.std_id where student0_.std_id=?
Premchand
Valmiki
Vyas 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us