Date in Hibernate Query Language in Hibernate 5


Copy JAR files which are listed below:

antlr-2.7.7.jar
classmate-1.3.4.jar
commons-lang3-3.6.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ehcache-core-2.6.11.jar
geolatte-geom-1.1.0.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.11.Final.jar
hibernate-ehcache-5.2.12.Final.jar
hibernate-ejb3-persistence.jar
hibernate-enhance-maven-plugin-4.3.7.Final.jar
hibernate-entitymanager.jar
hibernate-java8-5.2.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-spatial-5.2.11.Final.jar
hibernate-validator-6.0.2.Final.jar
javassist-3.16.1-GA.jar
jboss-logging-3.3.1.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jts-1.11.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.21.jar




Create a database with the name is hibernate5. This database have a table: Invoice table.

--
-- Table structure for table `invoice`
--

CREATE TABLE `invoice` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `dateCreated` date NOT NULL,
  `payment` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `invoice`
--

INSERT INTO `invoice` (`name`, `dateCreated`, `payment`) VALUES
('Invoice 1', '2017-12-08', 'cash');
INSERT INTO `invoice` (`name`, `dateCreated`, `payment`) VALUES
('Invoice 2', '2017-12-08', 'cash');
INSERT INTO `invoice` (`name`, `dateCreated`, `payment`) VALUES
('Invoice 3', '2017-12-05', 'cash');

Structures of Invoice Table

Invoice Table

Create a entity class – Invoice.java to represent the above table

Invoice.java

package entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "invoice")
public class Invoice implements java.io.Serializable {

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column
	private Integer id;

	@Column
	private String name;

	@Column
	private Date dateCreated;

	@Column
	private String payment;

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getDateCreated() {
		return dateCreated;
	}

	public void setDateCreated(Date dateCreated) {
		this.dateCreated = dateCreated;
	}

	public String getPayment() {
		return payment;
	}

	public void setPayment(String payment) {
		this.payment = payment;
	}

}




Hibernate Configuration File

Puts Invoice.java in your Hibernate configuration file, and also MySQL connection details.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.enable_lazy_load_no_trans">true</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.dialect">org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="entities.Invoice" />
	</session-factory>
</hibernate-configuration>

The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread.

package hibernate_query_language;

import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {
		try {
			StandardServiceRegistry standardRegistry = new
					StandardServiceRegistryBuilder()
					.configure("hibernate.cfg.xml")
					.build();
			Metadata metaData = new MetadataSources(
					standardRegistry)
					.getMetadataBuilder()
					.build();
			sessionFactory = metaData.getSessionFactoryBuilder().build();
		} catch (Throwable th) {
			throw new ExceptionInInitializerError(th);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;

	}
}

The InvoiceModel class contains methods to interact with the database.

package criteria_query;

import java.util.List;
import org.hibernate.*;
import entities.*;

public class InvoiceModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public List<Invoice> findByDate(int year, int month, int day) {
		List<Invoice> invoices = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			org.hibernate.query.Query query = session.createQuery(
					"from Invoice where year(dateCreated) = :year and month(dateCreated) = :month and day(dateCreated) = :day ");
			query.setParameter("year", year);
			query.setParameter("month", month);
			query.setParameter("day", day);
			invoices = query.getResultList();
			transaction.commit();
		} catch (Exception e) {
			invoices = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return invoices;
	}

}
package criteria_query;

import java.text.SimpleDateFormat;
import java.util.List;

import entities.Invoice;

public class Main {

	public static void main(String[] args) {

		InvoiceModel invoiceModel = new InvoiceModel();
		List<Invoice> invoices = invoiceModel.findByDate(2017, 12, 8);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		for (Invoice invoice : invoices) {
			System.out.println("Id: " + invoice.getId());
			System.out.println("Name: " + invoice.getName());
			System.out.println("Date Created: " + simpleDateFormat.format(invoice.getDateCreated()));
			System.out.println("Payment: " + invoice.getPayment());
			System.out.println("============================");
		}

	}

}




Id: 1
Name: Invoice 1
Date Created: 12/08/2017
Payment: cash
============================
Id: 2
Name: Invoice 2
Date Created: 12/08/2017
Payment: cash
============================