package net.roseindia.hqlexamples;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import net.roseindia.model.*;

/**
 * HQL Select Example In this example we will show you how you can use HQL
 * Between dates statement the datastore
 */

public class HQLDateBetween {

	public static void main(String[] args) throws Exception {
		/** Getting the Session Factory and session */
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = factory.getCurrentSession();
		/** Starting the Transaction */
		Transaction tx = session.beginTransaction();

		// Create HQL Between clause
		String HQL_QUERY = 
			"select i from Invoice i where i.invoiceDate between :start and :end ";

		Query query = session.createQuery(HQL_QUERY);

		String strDateFrom = "2010/10/25";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		Date dateFrom = formatter.parse(strDateFrom);

		String strDateTo = "2010/11/02";
		Date dateTo = formatter.parse(strDateTo);

		query.setParameter("start", dateFrom);
		query.setParameter("end", dateTo);
		List result = query.list();
		for (Iterator it = result.iterator(); it.hasNext();) {
			Invoice invoice = (Invoice) it.next();
			System.out.println("\nInvoice ID: " + invoice.getId());
			System.out.println("Invoice Date: " + invoice.getInvoiceDate());

		}

		/** Closing Session */
		session.close();
	}
}