Hibernate is a database independent technology, so the same code will work for all databases. It helps a Java developer write a query by mapping Java bean to database tables and help create tuned queries that boost performance. Even with limited SQL knowledge one can easily perform database operations. This makes the development faster and more accurate than JDBC. Hibernate supports useful features like connection pooling, caching, and inheritance etc.
This book will provide a useful hands-on guide to Hibernate to accomplish the development of a real-time Hibernate application.
We will start with the basics of Hibernate, which include setting up Hibernate – the pre-requisites and multiple ways of configuring Hibernate using Java. We will then dive deep into the fundamentals of Hibernate such as SessionFactory, session, criteria, working with objects and criteria. This will help a developer have a better understanding of how Hibernate works and what needs to be done to run a Hibernate application. Moving on, we will learn how to work with annotations, associations and collections. In the final chapters, we will see explore querying, advanced Hibernate concepts and integration with other frameworks.
To work with hibernate, we need a JAR (Java Archive) file provided by hibernate. Here, we will see how to download the hibernate core distribution. There are multiple ways to get the required libraries; here, we will consider two of them:
Manually downloading
Using Maven
Manually downloading
The first and most basic JAR file needed is a JDBC driver. The JDBC driver is a bridge or an API between Java and the database. The JDBC driver provides us with the generic classes that will help us communicate with the database. Generally, the driver is either provided by the database provider or developed by communities; however, you have to get it yourself. This also depends on the type of the database you are using. As we will use the MySQL database for this book, we will use the Mysql-Connector.jar file.
How to do it…
Let's come back to the library section. Apart from JDBC, you will need the JAR files for hibernate. Perform the following steps:
Download the hibernate core distribution from http://hibernate.org/orm/.
Now, place all the files in your classpath if you plan to run a standalone program and put them in the lib folder if it's a J2EE project.
Now, let's create the class that contains the annotation-based mapping. As we used the Employee class to provide XML-based mapping here, we will use the same class with annotations:
Represent the annotation-based mapping for the Employee class in Employee.java, as shown in the following code: