Hibernate is the object/relational mapping tool that handles mapping of Java classes to relational tables and Java types to SQL data type. It’s a well-known framework in the Enterprise Java eco-system since it’s being actively developed for the last 16 years.
With this article, I’m going to show the ways of using Hibernate inside a sample application – source code available here – and deploy it onto Payara Server. I will be using the latest version of Hibernate, which is 5.2.10.Final at the time of writing.
My sample project is a web application architected with Maven and it contains one simple domain object, its DAO implementation and its REST based web service for exposing CRUD operations to the outside world.
Let’s start with the Maven configuration of the project. Hibernate is added as a single dependency to the project since it transitively fetches the necessary dependencies underneath.
For demonstration purposes, the in-memory H2 database will be used for easy configuration. Its dependency definition is as follows:
The JDBC resource and Connection Pool definitions are defined in a glassfish-resources.xml file, which is located under the WEB-INF folder. This helps to isolate the definitions within our sample project, and mitigates needing to deal with the Payara Server Admin Console or asadmin commands to define the resources.
You can see that H2 database URL is defined as in-memory, and the JNDI name mapping that should be used by the project is jdbc/hibernate.
The persistence.xml file is used to register a persistence unit to the application at the application level. I am using the registered JDBC Resource that was defined in the glassfish-resources.xml file, and naming the persistence unit as payaraHibernate.
By defining the persistence provider, the application will use Hibernate as the underlying ORM. The H2 database is also related to the hibernate.dialect property so that it allows Hibernate to generate H2 optimized SQLs.
The Person domain object class is defined as follows:
The DAO implementation for the corresponding Person domain class is as follows:
The REST web service implementation is as follows:
After deploying the application onto Payara Server, I can easily invoke the REST web services for creating/updating/deleting person information. To invoke REST, I favored Postman , a GUI tool for API invocation. You can import given Postman project by yourself (see JSON file) and invoke endpoints deployed on localhost:8080. The URL for the endpoint would be http://localhost:8080/hibernate-example/resources/person for a local deployment.
The screenshot below shows the GET request on the provided URL.