Java Libraries
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 Database
Create a database with the name is hibernate5. This database have 1 table: MyTime table.
--
-- Table structure for table `mytime`
--
CREATE TABLE `mytime` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`date` date NOT NULL,
`dateTime` time NOT NULL,
`duration` bigint(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `mytime`
--
INSERT INTO `mytime` (`date`, `dateTime`, `duration`) VALUES
('2017-10-03', '18:15:05', 172800000000000);
INSERT INTO `mytime` (`date`, `dateTime`, `duration`) VALUES
('2017-10-11', '20:32:05', 172800000000000);
INSERT INTO `mytime` (`date`, `dateTime`, `duration`) VALUES
('2017-10-03', '16:45:05', 172800000000000);
Category Table
Product Table
Entities Class
Create a entity classes – MyTime.java to represent the above table
MyTime.java
package entities;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.*;
@Entity
@Table(name = "mytime")
public class MyTime implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private LocalDate date;
@Column
private LocalDateTime dateTime;
@Column
private Duration duration;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
}
Hibernate Configuration File
Puts MyTime.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.MyTime" />
</session-factory>
</hibernate-configuration>
Create HibernateUtil class
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_java8;
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;
}
}
Create MyTimeModel class
The MyTimeModel class contains methods to interact with the database.
package hibernate_java8;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.*;
import entities.*;
public class MyTimeModel {
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public Boolean create(MyTime myTime) {
Boolean result = true;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(myTime);
transaction.commit();
} catch (Exception e) {
result = false;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return result;
}
public List<MyTime> findAll() {
List<MyTime> myTimes = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("select m from MyTime m");
myTimes = query.getResultList();
transaction.commit();
} catch (Exception e) {
myTimes = null;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return myTimes;
}
public List<MyTime> search(LocalDate localDate) {
List<MyTime> myTimes = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("select m from MyTime m where m.date = :date");
query.setParameter("date", localDate);
myTimes = query.getResultList();
transaction.commit();
} catch (Exception e) {
myTimes = null;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return myTimes;
}
}
Run It
package hibernate_java8;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import entities.MyTime;
public class Demo {
public static void main(String[] args) {
MyTimeModel myTimeModel = new MyTimeModel();
System.out.println("Add New My Time");
MyTime newMyTime = new MyTime();
newMyTime.setDate(LocalDate.now());
newMyTime.setDateTime(LocalDateTime.now());
newMyTime.setDuration(Duration.ofDays(2));
System.out.println(myTimeModel.create(newMyTime));
System.out.println("Find All My Time");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("HH:mm");
for (MyTime myTime : myTimeModel.findAll()) {
System.out.println("Id: " + myTime.getId());
System.out.println("Date: " + dateTimeFormatter.format(myTime.getDate()));
System.out.println("Time: " + dateTimeFormatter2.format(myTime.getDateTime()));
System.out.println("Day: " + myTime.getDuration().toDays());
System.out.println("===================");
}
System.out.println("Search My Time with LocalDate");
for (MyTime myTime : myTimeModel.search(LocalDate.now())) {
System.out.println("Id: " + myTime.getId());
System.out.println("Date: " + dateTimeFormatter.format(myTime.getDate()));
System.out.println("Time: " + dateTimeFormatter2.format(myTime.getDateTime()));
System.out.println("Day: " + myTime.getDuration().toDays());
System.out.println("===================");
}
}
}
Output
Add New My Time
true
Find All My Time
Id: 1
Date: 03/10/2017
Time: 16:45
Day: 2
===================
Id: 2
Date: 11/10/2017
Time: 16:45
Day: 2
===================
Id: 3
Date: 03/10/2017
Time: 16:45
Day: 2
===================
Id: 4
Date: 06/12/2017
Time: 14:58
Day: 2
===================
Id: 5
Date: 06/12/2017
Time: 15:00
Day: 2
===================
Search My Time With LocalDate
Id: 4
Date: 06/12/2017
Time: 14:58
Day: 2
===================
Id: 5
Date: 06/12/2017
Time: 15:00
Day: 2
===================