package net.roseindia.main;

import java.util.Iterator;
import java.util.List;

import net.roseindia.bean.Student;
import net.roseindia.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class OrderByExample {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();

		Object object;

		try {
			// Creating a Criteria instance

			Criteria criteria = session.createCriteria(Student.class);
			criteria.add(Restrictions.lt("rollNo", 10));
			criteria.addOrder(Order.desc("rollNo"));
			List list = criteria.list();
			
			Iterator itr = list.iterator();
			System.out.println("\n");
			System.out.println("Student Details In descending Order :- \n");
			System.out.println("\tRoll No"+"\t"+"Name"+"\t"+ "Course"+"\t"+ "Address\n");
			if (list.size() == 0) {
				System.out.println("No Result Found !");
			}
			while (itr.hasNext()) {
				object = (Object) itr.next();
				System.out.printf("\t");
				System.out.println(((Student) object).getRollNo()+"\t"+ ((Student) object).getName()+"\t"+ ((Student) object).getCourse()+"\t"+ ((Student) object).getAddress());
				}
			
			criteria.addOrder(Order.asc("rollNo"));
			List list1 = criteria.list();
			
			Iterator itr1 = list.iterator();
			System.out.println("\n");
			System.out.println("Student Details In Ascending Order :- \n");
			System.out.println("\tRoll No"+"\t"+"Name"+"\t"+ "Course"+"\t"+ "Address\n");
			if (list.size() == 0) {
				System.out.println("No Result Found !");
			}
			while (itr1.hasNext()) {
				object = (Object) itr1.next();
				System.out.printf("\t");
				System.out.println(((Student) object).getRollNo()+"\t"+ ((Student) object).getName()+"\t"+ ((Student) object).getCourse()+"\t"+ ((Student) object).getAddress());
				}

		} catch (HibernateException e) {

			e.printStackTrace();
		} finally {
			session.close();
		}

	}
}
