diff --git a/persistence-modules/hibernate5-queries/README.md b/persistence-modules/hibernate5-queries/README.md
new file mode 100644
index 0000000000..1edf4ded1e
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/README.md
@@ -0,0 +1,10 @@
+## Hibernate 5
+
+This module contains articles about Hibernate 5.
+
+### Relevant articles:
+
+- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
+- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
+- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
+- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/pom.xml b/persistence-modules/hibernate5-queries/pom.xml
new file mode 100644
index 0000000000..544d22c0a3
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/pom.xml
@@ -0,0 +1,82 @@
+
+
+ 4.0.0
+ hibernate5-queries
+ 0.0.1-SNAPSHOT
+ hibernate5-queries
+
+
+ com.baeldung
+ persistence-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.hibernate
+ hibernate-core
+ ${hibernate.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj-core.version}
+ test
+
+
+ com.h2database
+ h2
+ ${h2.version}
+
+
+ org.hibernate
+ hibernate-spatial
+ ${hibernate.version}
+
+
+ org.opengeo
+ geodb
+ ${geodb.version}
+
+
+ mysql
+ mysql-connector-java
+ ${mysql.version}
+
+
+ ch.vorburger.mariaDB4j
+ mariaDB4j
+ ${mariaDB4j.version}
+
+
+ org.hibernate
+ hibernate-testing
+ ${hibernate.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${openjdk-jmh.version}
+
+
+
+
+
+ geodb-repo
+ GeoDB repository
+ http://repo.boundlessgeo.com/main/
+
+
+
+
+ 5.3.7.Final
+ 6.0.6
+ 2.2.3
+ 3.8.0
+ 0.9
+ 1.21
+
+
+
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java
new file mode 100644
index 0000000000..58724e690c
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -0,0 +1,73 @@
+package com.baeldung.hibernate;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Properties;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.service.ServiceRegistry;
+
+import com.baeldung.hibernate.customtypes.LocalDateStringType;
+import com.baeldung.hibernate.entities.DeptEmployee;
+import com.baeldung.hibernate.pojo.Student;
+
+public class HibernateUtil {
+ private static String PROPERTY_FILE_NAME;
+
+ public static SessionFactory getSessionFactory() throws IOException {
+ return getSessionFactory(null);
+ }
+
+ public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
+ PROPERTY_FILE_NAME = propertyFileName;
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ return makeSessionFactory(serviceRegistry);
+ }
+
+ public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
+ ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
+ return makeSessionFactory(serviceRegistry);
+ }
+
+ private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+
+ metadataSources.addPackage("com.baeldung.hibernate.pojo");
+ metadataSources.addAnnotatedClass(Student.class);
+ metadataSources.addAnnotatedClass(DeptEmployee.class);
+ metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
+
+ Metadata metadata = metadataSources.getMetadataBuilder()
+ .applyBasicType(LocalDateStringType.INSTANCE)
+ .build();
+
+ return metadata.getSessionFactoryBuilder()
+ .build();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ return configureServiceRegistry(getProperties());
+ }
+
+ private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
+ return new StandardServiceRegistryBuilder().applySettings(properties)
+ .build();
+ }
+
+ public static Properties getProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread()
+ .getContextClassLoader()
+ .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java
new file mode 100644
index 0000000000..99d9505ea3
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java
@@ -0,0 +1,8 @@
+package com.baeldung.hibernate;
+
+public class UnsupportedTenancyException extends Exception {
+ public UnsupportedTenancyException (String message) {
+ super(message);
+ }
+
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java
new file mode 100644
index 0000000000..35cfe55ba6
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/HibernateUtil.java
@@ -0,0 +1,60 @@
+package com.baeldung.hibernate.criteriaquery;
+
+import com.baeldung.hibernate.customtypes.LocalDateStringType;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.service.ServiceRegistry;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Properties;
+
+public class HibernateUtil {
+ private static SessionFactory sessionFactory;
+
+ private HibernateUtil() {
+ }
+
+ public static SessionFactory getSessionFactory() {
+ if (sessionFactory == null) {
+ sessionFactory = buildSessionFactory();
+ }
+ return sessionFactory;
+ }
+
+ private static SessionFactory buildSessionFactory() {
+ try {
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+
+ metadataSources.addAnnotatedClass(Student.class);
+ Metadata metadata = metadataSources.getMetadataBuilder()
+ .applyBasicType(LocalDateStringType.INSTANCE)
+ .build();
+ return metadata.getSessionFactoryBuilder().build();
+ } catch (IOException ex) {
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
+
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties).build();
+ }
+
+ private static Properties getProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread()
+ .getContextClassLoader()
+ .getResource("hibernate.properties");
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java
new file mode 100644
index 0000000000..314e7ca557
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java
@@ -0,0 +1,58 @@
+package com.baeldung.hibernate.criteriaquery;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "students")
+public class Student {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private int id;
+
+ @Column(name = "first_name")
+ private String firstName;
+
+ @Column(name = "last_name")
+ private String lastName;
+
+ @Column(name = "grad_year")
+ private int gradYear;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public int getGradYear() {
+ return gradYear;
+ }
+
+ public void setGradYear(int gradYear) {
+ this.gradYear = gradYear;
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
new file mode 100644
index 0000000000..56be9e693f
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
@@ -0,0 +1,51 @@
+package com.baeldung.hibernate.customtypes;
+
+import org.hibernate.type.LocalDateType;
+import org.hibernate.type.descriptor.WrapperOptions;
+import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
+import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
+import org.hibernate.type.descriptor.java.MutabilityPlan;
+
+import java.time.LocalDate;
+
+public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor {
+
+ public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
+
+ public LocalDateStringJavaDescriptor() {
+ super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
+ }
+
+ @Override
+ public String toString(LocalDate value) {
+ return LocalDateType.FORMATTER.format(value);
+ }
+
+ @Override
+ public LocalDate fromString(String string) {
+ return LocalDate.from(LocalDateType.FORMATTER.parse(string));
+ }
+
+ @Override
+ public X unwrap(LocalDate value, Class type, WrapperOptions options) {
+
+ if (value == null)
+ return null;
+
+ if (String.class.isAssignableFrom(type))
+ return (X) LocalDateType.FORMATTER.format(value);
+
+ throw unknownUnwrap(type);
+ }
+
+ @Override
+ public LocalDate wrap(X value, WrapperOptions options) {
+ if (value == null)
+ return null;
+
+ if(String.class.isInstance(value))
+ return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
+
+ throw unknownWrap(value.getClass());
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java
new file mode 100644
index 0000000000..c8d37073e8
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.customtypes;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.type.AbstractSingleColumnStandardBasicType;
+import org.hibernate.type.DiscriminatorType;
+import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
+import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
+
+import java.time.LocalDate;
+
+public class LocalDateStringType extends AbstractSingleColumnStandardBasicType implements DiscriminatorType {
+
+ public static final LocalDateStringType INSTANCE = new LocalDateStringType();
+
+ public LocalDateStringType() {
+ super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
+ }
+
+ @Override
+ public String getName() {
+ return "LocalDateString";
+ }
+
+ @Override
+ public LocalDate stringToObject(String xml) throws Exception {
+ return fromString(xml);
+ }
+
+ @Override
+ public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
+ return '\'' + toString(value) + '\'';
+ }
+
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java
new file mode 100644
index 0000000000..ff94f4f849
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/Department.java
@@ -0,0 +1,45 @@
+package com.baeldung.hibernate.entities;
+
+import java.util.List;
+
+import javax.persistence.*;
+
+@Entity
+public class Department {
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ private long id;
+
+ private String name;
+
+ @OneToMany(mappedBy="department")
+ private List employees;
+
+ public Department(String name) {
+ this.name = name;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getEmployees() {
+ return employees;
+ }
+
+ public void setEmployees(List employees) {
+ this.employees = employees;
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
new file mode 100644
index 0000000000..6510e70650
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
@@ -0,0 +1,83 @@
+package com.baeldung.hibernate.entities;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
+ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
+ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
+ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
+@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
+ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) })
+@Entity
+public class DeptEmployee {
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ private long id;
+
+ private String employeeNumber;
+
+ private String title;
+
+ private String name;
+
+ @ManyToOne
+ private Department department;
+
+ public DeptEmployee(String name, String employeeNumber, Department department) {
+ this.name = name;
+ this.employeeNumber = employeeNumber;
+ this.department = department;
+ }
+
+ public DeptEmployee(String name, String employeeNumber, String title, Department department) {
+ super();
+ this.name = name;
+ this.employeeNumber = employeeNumber;
+ this.title = title;
+ this.department = department;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getEmployeeNumber() {
+ return employeeNumber;
+ }
+
+ public void setEmployeeNumber(String employeeNumber) {
+ this.employeeNumber = employeeNumber;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Department getDepartment() {
+ return department;
+ }
+
+ public void setDepartment(Department department) {
+ this.department = department;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java
new file mode 100644
index 0000000000..cc0c234df0
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/findall/FindAll.java
@@ -0,0 +1,35 @@
+package com.baeldung.hibernate.findall;
+
+import java.util.List;
+
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Root;
+
+import org.hibernate.Session;
+
+import com.baeldung.hibernate.pojo.Student;
+
+public class FindAll {
+
+ private Session session;
+
+ public FindAll(Session session) {
+ super();
+ this.session = session;
+ }
+
+ public List findAllWithJpql() {
+ return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
+ }
+
+ public List findAllWithCriteriaQuery() {
+ CriteriaBuilder cb = session.getCriteriaBuilder();
+ CriteriaQuery cq = cb.createQuery(Student.class);
+ Root rootEntry = cq.from(Student.class);
+ CriteriaQuery all = cq.select(rootEntry);
+ TypedQuery allQuery = session.createQuery(all);
+ return allQuery.getResultList();
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java
new file mode 100644
index 0000000000..9b26c117eb
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/java/com/baeldung/hibernate/pojo/Student.java
@@ -0,0 +1,51 @@
+package com.baeldung.hibernate.pojo;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Student {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.SEQUENCE)
+ private long studentId;
+
+ private String name;
+
+ private int age;
+
+ public Student() {
+ }
+
+ public Student(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public long getStudentId() {
+ return studentId;
+ }
+
+ public void setStudentId(long studentId) {
+ this.studentId = studentId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+}
diff --git a/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml
new file mode 100644
index 0000000000..474eeb7a44
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/resources/META-INF/persistence.xml
@@ -0,0 +1,18 @@
+
+
+
+ Hibernate EntityManager Demo
+ true
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql b/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql
new file mode 100644
index 0000000000..b2848aa256
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/resources/init_database.sql
@@ -0,0 +1,10 @@
+CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.SQLException;
+@CODE
+void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException {
+ CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'");
+ updateStatement.execute();
+}
+$$;
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/main/resources/logback.xml b/persistence-modules/hibernate5-queries/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java
new file mode 100644
index 0000000000..cb73fe348c
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/NamedQueryIntegrationTest.java
@@ -0,0 +1,98 @@
+package com.baeldung.hibernate;
+
+import com.baeldung.hibernate.entities.Department;
+import com.baeldung.hibernate.entities.DeptEmployee;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.query.NativeQuery;
+import org.hibernate.query.Query;
+import org.junit.*;
+
+import java.io.IOException;
+
+public class NamedQueryIntegrationTest {
+ private static Session session;
+
+ private Transaction transaction;
+
+ private Long purchaseDeptId;
+
+ @BeforeClass
+ public static void setUpClass() throws IOException {
+ session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession();
+ }
+
+ @Before
+ public void setUp() throws IOException {
+ transaction = session.beginTransaction();
+ session.createNativeQuery("delete from deptemployee").executeUpdate();
+ session.createNativeQuery("delete from department").executeUpdate();
+ Department salesDepartment = new Department("Sales");
+ Department purchaseDepartment = new Department("Purchase");
+ DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment);
+ DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment);
+ DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment);
+ session.persist(salesDepartment);
+ session.persist(purchaseDepartment);
+ purchaseDeptId = purchaseDepartment.getId();
+ session.persist(employee1);
+ session.persist(employee2);
+ session.persist(employee3);
+ transaction.commit();
+ transaction = session.beginTransaction();
+ }
+
+ @After
+ public void tearDown() {
+ if(transaction.isActive()) {
+ transaction.rollback();
+ }
+ }
+
+ @Test
+ public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() {
+ Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class);
+ query.setParameter("employeeNo", "001");
+ DeptEmployee result = query.getSingleResult();
+ Assert.assertNotNull(result);
+ Assert.assertEquals("John Wayne", result.getName());
+ }
+
+ @Test
+ public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() {
+ Query query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class);
+ query.setParameter("name", "John Wayne");
+ DeptEmployee result = query.getSingleResult();
+ Assert.assertNotNull(result);
+ Assert.assertEquals("001", result.getEmployeeNumber());
+ }
+
+ @Test
+ public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() {
+ @SuppressWarnings("rawtypes")
+ NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName");
+ query.setParameter("name", "John Wayne");
+ DeptEmployee result = (DeptEmployee) query.getSingleResult();
+ Assert.assertNotNull(result);
+ Assert.assertEquals("001", result.getEmployeeNumber());
+ }
+
+ @Test
+ public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() {
+ Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment");
+ spQuery.setParameter("employeeNo", "001");
+ Department newDepartment = session.find(Department.class, purchaseDeptId);
+ spQuery.setParameter("newDepartment", newDepartment);
+ spQuery.executeUpdate();
+ transaction.commit();
+ }
+
+ @Test
+ public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() {
+ Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation");
+ spQuery.setParameter("employeeNumber", "002");
+ spQuery.setParameter("newDesignation", "Supervisor");
+ spQuery.executeUpdate();
+ transaction.commit();
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java
new file mode 100644
index 0000000000..cedba412d9
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.hibernate.criteriaquery;
+
+import com.baeldung.hibernate.criteriaquery.HibernateUtil;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.query.Query;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Root;
+import java.io.IOException;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+
+public class TypeSafeCriteriaIntegrationTest {
+
+ private static SessionFactory sessionFactory;
+
+ private Session session;
+
+ @BeforeClass
+ public static void beforeTests() throws IOException {
+ sessionFactory = HibernateUtil.getSessionFactory();
+ }
+
+ @Before
+ public void setUp() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ }
+
+ @Test
+ public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() {
+
+ prepareData();
+ CriteriaBuilder cb = session.getCriteriaBuilder();
+ CriteriaQuery criteriaQuery = cb.createQuery(Student.class);
+
+ Root root = criteriaQuery.from(Student.class);
+ criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));
+
+ Query query = session.createQuery(criteriaQuery);
+ List results = query.getResultList();
+
+ assertNotNull(results);
+ assertEquals(1, results.size());
+
+ Student student = results.get(0);
+
+ assertEquals("Ken", student.getFirstName());
+ assertEquals("Thompson", student.getLastName());
+ assertEquals(1965, student.getGradYear());
+ }
+
+ private void prepareData() {
+ Student student1 = new Student();
+ student1.setFirstName("Ken");
+ student1.setLastName("Thompson");
+ student1.setGradYear(1965);
+
+ session.save(student1);
+
+ Student student2 = new Student();
+ student2.setFirstName("Dennis");
+ student2.setLastName("Ritchie");
+ student2.setGradYear(1963);
+
+ session.save(student2);
+ session.getTransaction().commit();
+ }
+
+ @After
+ public void tearDown() {
+ session.close();
+ }
+
+ @AfterClass
+ public static void afterTests() {
+ sessionFactory.close();
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java
new file mode 100644
index 0000000000..8a1b9e9791
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/findall/FindAllUnitTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.hibernate.findall;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.hibernate.HibernateUtil;
+import com.baeldung.hibernate.pojo.Student;
+
+public class FindAllUnitTest {
+
+ private Session session;
+ private Transaction transaction;
+
+ private FindAll findAll;
+
+ @Before
+ public void setUp() throws IOException {
+
+ session = HibernateUtil.getSessionFactory().openSession();
+ transaction = session.beginTransaction();
+ findAll = new FindAll(session);
+
+ session.createNativeQuery("delete from Student").executeUpdate();
+
+ Student student1 = new Student();
+ session.persist(student1);
+
+ Student student2 = new Student();
+ session.persist(student2);
+
+ Student student3 = new Student();
+ session.persist(student3);
+
+ transaction.commit();
+ transaction = session.beginTransaction();
+ }
+
+ @After
+ public void tearDown() {
+ transaction.rollback();
+ session.close();
+ }
+
+ @Test
+ public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() {
+ List list = findAll.findAllWithCriteriaQuery();
+ assertEquals(3, list.size());
+ }
+
+ @Test
+ public void givenJpql_WhenFindAll_ThenGetAllPersons() {
+ List list = findAll.findAllWithJpql();
+ assertEquals(3, list.size());
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java
new file mode 100644
index 0000000000..13eae3d877
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/java/com/baeldung/hibernate/queryplancache/QueryPlanCacheBenchmark.java
@@ -0,0 +1,106 @@
+package com.baeldung.hibernate.queryplancache;
+
+import com.baeldung.hibernate.HibernateUtil;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.jpa.QueryHints;
+import org.hibernate.query.Query;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+import org.openjdk.jmh.runner.RunnerException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+public class QueryPlanCacheBenchmark {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class);
+
+ @State(Scope.Thread)
+ public static class QueryPlanCacheBenchMarkState {
+ @Param({"1", "2", "3"})
+ public int planCacheSize;
+
+ public Session session;
+
+ @Setup
+ public void stateSetup() throws IOException {
+ LOGGER.info("State - Setup");
+ session = initSession(planCacheSize);
+ LOGGER.info("State - Setup Complete");
+ }
+
+ private Session initSession(int planCacheSize) throws IOException {
+ Properties properties = HibernateUtil.getProperties();
+ properties.put("hibernate.query.plan_cache_max_size", planCacheSize);
+ properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize);
+ SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
+ return sessionFactory.openSession();
+ }
+
+ @TearDown
+ public void tearDownState() {
+ LOGGER.info("State - Teardown");
+ SessionFactory sessionFactory = session.getSessionFactory();
+ session.close();
+ sessionFactory.close();
+ LOGGER.info("State - Teardown complete");
+ }
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.MICROSECONDS)
+ @Fork(1)
+ @Warmup(iterations = 2)
+ @Measurement(iterations = 5)
+ public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) {
+
+ Query query1 = findEmployeesByDepartmentNameQuery(state.session);
+ Query query2 = findEmployeesByDesignationQuery(state.session);
+ Query query3 = findDepartmentOfAnEmployeeQuery(state.session);
+
+ blackhole.consume(query1);
+ blackhole.consume(query2);
+ blackhole.consume(query3);
+
+ }
+
+ private Query findEmployeesByDepartmentNameQuery(Session session) {
+ return session.createQuery("SELECT e FROM DeptEmployee e " +
+ "JOIN e.department WHERE e.department.name = :deptName")
+ .setMaxResults(30)
+ .setHint(QueryHints.HINT_FETCH_SIZE, 30);
+ }
+
+ private Query findEmployeesByDesignationQuery(Session session) {
+ return session.createQuery("SELECT e FROM DeptEmployee e " +
+ "WHERE e.title = :designation")
+ .setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000);
+ }
+
+ private Query findDepartmentOfAnEmployeeQuery(Session session) {
+ return session.createQuery("SELECT e.department FROM DeptEmployee e " +
+ "JOIN e.department WHERE e.employeeNumber = :empId");
+
+ }
+
+ public static void main(String... args) throws IOException, RunnerException {
+ //main-class to run the benchmark
+ org.openjdk.jmh.Main.main(args);
+ }
+}
diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties
new file mode 100644
index 0000000000..c14782ce0f
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-customtypes.properties
@@ -0,0 +1,14 @@
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
+hibernate.connection.username=sa
+hibernate.connection.autocommit=true
+jdbc.password=
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
+
+hibernate.c3p0.min_size=5
+hibernate.c3p0.max_size=20
+hibernate.c3p0.acquire_increment=5
+hibernate.c3p0.timeout=1800
diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties
new file mode 100644
index 0000000000..457f965347
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate-namedquery.properties
@@ -0,0 +1,9 @@
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql'
+hibernate.connection.username=sa
+hibernate.connection.autocommit=true
+jdbc.password=
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties b/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties
new file mode 100644
index 0000000000..c14782ce0f
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/resources/hibernate.properties
@@ -0,0 +1,14 @@
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
+hibernate.connection.username=sa
+hibernate.connection.autocommit=true
+jdbc.password=
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.show_sql=true
+hibernate.hbm2ddl.auto=create-drop
+
+hibernate.c3p0.min_size=5
+hibernate.c3p0.max_size=20
+hibernate.c3p0.acquire_increment=5
+hibernate.c3p0.timeout=1800
diff --git a/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql
new file mode 100644
index 0000000000..c0c9a3f34d
--- /dev/null
+++ b/persistence-modules/hibernate5-queries/src/test/resources/lifecycle-init.sql
@@ -0,0 +1,25 @@
+create sequence hibernate_sequence start with 1 increment by 1;
+
+create table Football_Player (
+ id bigint not null,
+ name varchar(255),
+ primary key (id)
+);
+
+insert into
+ Football_Player
+ (name, id)
+ values
+ ('Cristiano Ronaldo', next value for hibernate_sequence);
+
+insert into
+ Football_Player
+ (name, id)
+ values
+ ('Lionel Messi', next value for hibernate_sequence);
+
+insert into
+ Football_Player
+ (name, id)
+ values
+ ('Gigi Buffon', next value for hibernate_sequence);
\ No newline at end of file
diff --git a/persistence-modules/hibernate5-queries/src/test/resources/profile.png b/persistence-modules/hibernate5-queries/src/test/resources/profile.png
new file mode 100644
index 0000000000..1cd4e978b9
Binary files /dev/null and b/persistence-modules/hibernate5-queries/src/test/resources/profile.png differ