0% found this document useful (0 votes)
292 views

Java Hibernate Cookbook - Sample Chapter

Chapter No. 1 - Setting Up Hibernate Over 50 recipes to help you build dynamic and powerful real-time Java Hibernate applications For more information : http://bit.ly/1OebyKD

Uploaded by

Packt Publishing
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
292 views

Java Hibernate Cookbook - Sample Chapter

Chapter No. 1 - Setting Up Hibernate Over 50 recipes to help you build dynamic and powerful real-time Java Hibernate applications For more information : http://bit.ly/1OebyKD

Uploaded by

Packt Publishing
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Fr

ee

Java Hibernate Cookbook

This book is a useful hands-on guide to developing 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 concepts such as SessionFactory, sessions,
criteria, and working with objects. Moving on, we will learn how to work with annotations, associations, and
collections. In the final chapters, we will explore advanced hibernate concepts, querying, and integration
with other frameworks.

What this book will do


for you...
Set up and install hibernate on your system
and explore different ways in which hibernate
can be configured
Learn the basic concepts and fundamentals
of Java Hibernate
Define mappings without the use of XML files
by using annotations
Persist collection elements such as list, map,
set and array
Explore the various mapping options and
learn to work with hibernate associations
Understand advanced hibernate concepts
such as caching and inheritance
Develop an engaging and robust real-world
hibernate application based on a common
business scenario

A straightforward and easy-to-follow format

A selection of the most important tasks


and problems
Carefully organized instructions to solve
problems efficiently
Clear explanations of what you did
Solutions that can be applied to solve
real-world problems

$ 44.99 US
28.99 UK

community experience distilled

P U B L I S H I N G

Prices do not include


local sales tax or VAT
where applicable

P U B L I S H I N G

Visit www.PacktPub.com for books, eBooks,


code, downloads, and PacktLib.

Yogesh Prajapati
Vishal Ranapariya

Integrate hibernate with other frameworks to


develop robust enterprise applications

Inside the Cookbook...

Java Hibernate Cookbook

Hibernate is a database-independent technology that helps developers write queries by mapping Java
beans to database tables to create tuned queries that boost performance.

Sa

pl
e

Quick answers to common problems

Java Hibernate
Cookbook
Over 50 recipes to help you build dynamic and powerful real-time
Java Hibernate applications

Yogesh Prajapati
Vishal Ranapariya

In this package, you will find:

The author biography


A preview chapter from the book, Chapter 1 'Setting Up Hibernate'
A synopsis of the books content
More information on Java Hibernate Cookbook

About the Authors


Yogesh Prajapati is a Java programmer. He has more than 4 years of experience in
implementing enterprise web applications using J2EE technologies. Yogesh has experience in
technologies and frameworks such as Spring, Hibernate, RESTful Web Services, and MongoDB.
He pursued a BCA from Ganpat University, Kherva, Gujarat, India. In 2011, Yogesh obtained a
master's degree in computer application from Gujarat University, Gujarat, India.
Yogesh's expertise is not limited to a particular domain; he has worked with clients in the
transportation, finance, and health care domains. Apart from this, he has had experience in
GIS development and has also worked in the hospitality industry.
Yogesh has a blog, http://kode12.com, where he shares his knowledge of Java and other
technologies. He is interested in contributing to open source technologies and is enthusiastic
about building new products and services. You can follow Yogesh on his blog and on Linkedin
at http://in.linkedin.com/in/yogeshmprajapati.

Vishal Ranapariya is a Java developer. He has more than 4 years of experience in


implementing enterprise web applications using J2EE technology. He has experience with
technologies and frameworks such as Java, J2EE, Spring, Hibernate, RESTful web services,
MongoDB, and Core Hadoop.
Vishal pursued a BCA from Gujarat University, Gujarat, India. In 2011, he obtained a master's
degree in computer application from Gujarat University, Gujarat, India.
Vishal has blogs at http://kode12.com, where he shares his knowledge of Java-related
open source technologies. He is interested in contributing to open source technologies. Vishal
is enthusiastic about building new products and services. You can follow Vishal on his blog
and on LinkedIn at https://in.linkedin.com/in/vishalranapariya.

Preface
There are multiple databases available to store our valuable data. When we go for relational
data structures, we can perform any operation on the data using queries on the interface
provided by the database vendor or using a third party tool. The syntax for all databases is
almost similar, but some databases follow their own syntax and semantics of writing a query.
Nowadays, real-world applications require a quick development cycle, database-independent
query execution, and a generic code that can be supported by multiple databases. It's a very
hard and time-consuming task for a software developer to fulfill this set of requirements.
Hibernate is an ORM (Object Relational Mapping) tool that helps us by making our development
process faster and making the software development independent of the database; so, we
can easily change a database vendor without worrying about the changes required in code.
Therefore, whether you are developing a standalone Java application or a server-side Java
Enterprise application, you could use hibernate to make your code database-independent.
Java Hibernate Cookbook will help you to learn hibernate from the basics to an advanced
level. In this book, we will try to create simple and short recipes to understand hibernate
step by step.

What this book covers


Chapter 1, Setting Up Hibernate, provides the basics of hibernate and the persistent class.
Next, you will learn to obtain the required libraries, XML and annotation-based configuration,
and the mapping required for hibernate.
Chapter 2, Understanding the Fundamentals, takes you through the basic objects required
to start working with hibernate, such as SessionFactory, Session, Criteria,
Projection, and so on.
Chapter 3, Basic Annotations, covers the very basic annotations that are useful and
necessary while writing with hibernate, such as declaring table (@Table), declaring column
(@Column), declaring primary key (@Id), and so on.

Preface
Chapter 4, Working with Collections, explains how collections work with hibernate and how to
persist Java collections such as List, Map, Set, and so on using hibernate.
Chapter 5, Working With Associations, helps you to understand relationships and associations
such as one-to-one, one-to-many (many-to-one), and many-to-many. In this chapter, you will
discover the simplest way to implement a relationship using hibernate.
Chapter 6, Querying, applies the basics of hibernate to query a database. This chapter helps
you to understand the fundamentals of hibernate such as alias, subquery, NamedQuery,
formula, and HQL.
Chapter 7, Advanced Concepts, helps you to learn the advanced concepts in hibernate such
as caching, inheritance strategy, versioning, and maintaining the history of the objects.
Chapter 8, Integration with Other Frameworks, explains integration with other MVC frameworks
such as Struts and Spring. It shows how to achieve a persistent life cycle in the frameworks.

Setting Up Hibernate
In this chapter, we will cover the following recipes:
f

Getting the required libraries for hibernate

Creating a hibernate persistent class

Providing an XML-based hibernate mapping

Providing an annotation-based hibernate mapping

Providing a hibernate configuration using an XML file

Providing a hibernate configuration using a properties file

Configuring hibernate programmatically

Introduction
In this chapter, we will take a look at how the hibernate and ORM (Object-relational Mapping)
frameworks work, how to configure hibernate in different ways, and the libraries that are
required for the hibernate application. An essential part of the application is the hibernate
configuration. Through the configuration, we can provide database information to the
hibernate engine, such as the database host, port, username, password, the database name,
the drive class, and so on.
In the older era of Java development, developers used some methodologies to persist data.
To persist data means to save or store data in some storage medium by maintaining it in
a certain state. Once the data is successfully persisted, it can be used at any given time. A
database is the more preferable storage medium for a transactional operation. Usually, we
use JDBC (Java Database Connectivity) to perform such operation with the database.

Setting Up Hibernate
If we use the JDBC operation, we need to work a bit harder and take care of the
following processes:
f

Opening a database connection

Maintaining an open connection

Building a query

Executing a query

Getting a response to the query

Mapping the query response with the custom classes

Closing the database connection

To avoid this hectic process, we can use the ORM tools available in the market. ORM stands
for Object Relation Mapping. It works as a bridge between the application and database by
simplifying the communication between them.
The benefits of the ORM framework are as follows:
f

It reduces the development time/cost.

It speeds up the development.

It provides us with portability. Hibernate supports multiple databases, so there is no


need to write a database-specific code.

This is a useful feature of hibernate. Generally, all databases have their own syntax made up
of Data Definition Language (DDL) or Data Manipulation Language (DML) statements. If
we used JDBC, we would need to write a database-specific code as our database is changed.
However, hibernate gets rid of the developer's headache by handling this issue.
The syntax of a query may be different for different database parameters; still, hibernate
works in the same way for all types of databases. Hibernate's term dialect helps achieve
this type of functionality. The implementation of the dialect class is provided by the
database provider to inform hibernate about the syntax of this particular database.
Some useful features of hibernate are as follows:
f

Code reusability

Transaction management

Efficient collection/custom classes mapping

The caching mechanism supported by hibernate

Chapter 1

Getting the required libraries for hibernate


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:
f

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:
1. Download the hibernate core distribution from http://hibernate.org/orm/.
2. 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.
When you manually download the libraries, it's the programmer's
responsibility to get all the required and dependent JAR files from
the official site of hibernate; failing this, they will face errors.

Using Maven
If you use the Maven project, it would get rid of your headache of finding all the JAR files
for hibernate and the dependent libraries. You can use the following Maven configuration
for hibernate.

Setting Up Hibernate

How to do it
1. Enter the following code into the pom.xml source file to show the dependency
mapping of hibernate and MySQL in pom.xml:

<dependencies>
<!-- MySQL connector -->
<dependency>
<groupId>MySQL</groupId>
<artifactId>MySQL-connector-Java</artifactId>
<version>MySQL-connector-version</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>hibernate-version</version>
</dependency>
<dependencies>

Using this method, Maven will download all the required JAR files related to hibernate and the
dependent libraries required for hibernate.
Replace MySQL-connector-version with your required MySQL connector
version in the <version>MySQL-connector-version</version>
line, and replace hibernate-version with your required hibernate version in
the <version>hibernate-version</version> line.

Creating a hibernate persistent class


As discussed in the Preface, the developer will be dealing with objects at every step of
development. Also, when we use hibernate, we don't need to work on a core SQL query. Here,
we will create a POJO (Plain Old Java Object) in Java, which represents a table in the database.

Getting ready
By POJO, we mean that we will create a Java class that satisfies the following requirements:
f

It needs to have a default constructor that is persistent.

It should contain the id attribute. ID is used to identify the object and is mapped with
the primary column of a table.

All attributes should have Getter and Setter methods, such as getXXX and
setXXX where xxx is a field name.

Chapter 1

How to do it...
We will now create a persistent class and name it Employee. The following table shows a
representation of the Employee class:
Employee
id
firstName
salary

1. Create the Employee.java class and place the following code in the class:
public class Employee{
private long id;
private String firstName;
private double salary;
// other fields
// default constructor
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
5

Setting Up Hibernate
}
//
// Getter and setter for other fields...
//
}

Now the preceding class satisfies all the requirements listed before to be a persistent class.
The preceding class now contains the following:
f

The default Employee() constructor

The id attribute, which is the primary column of the table and can be used to
uniquely identify an entry

The individual getters and setters in all the attributes (id, firstName, and salary)

There's more
Now, let's see how to design a POJO for tables having references between the Department
and Employee tables:
Department
id

Employee
id

deptName

firstName
salary
department

The following code is the definition for the Department class in Department.java:
public class Department{
private long id;
private String deptName;
//default constructor
public void Department(){
}
//getters and setters
public long getId() {
return id;
}
public void setId(long id) {
6

Chapter 1
this.id = id;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}

The following code is the definition for the Employee class in Employee.java:
public class Employee{
private long id;
private String firstName;
private double salary;
private Department department; // reference to Department.
//default constructor
public void Employee(){
}
//getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public double getSalary() {
return salary;
}
7

Setting Up Hibernate
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDepartment(){
return department;
}
public setDepartment(Department department){
this.department = department;
}
}

Downloading the example code


You can download the example code files for all Packt
books you have purchased from your account at
http://www.packtpub.com. If you purchased
this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the
files e-mailed directly to you.

Providing an XML-based hibernate mapping


In the preceding recipe, you learned how to create a POJO. Now we will consider how to create
the configuration for hibernate. There are multiple ways of mapping, and this is one of them.
Generally, the configuration provides the following information:
f

The mapping between the POJO and the database table

The mapping between the POJO property and the database table column

The definition of the primary key column

The definitions of the foreign key column and relationships such as one-to-one,
one-to-many, many-to-one, many-to-many with another table, and so on

Constraints such as not-null, formula, lazy, cascade, and so on

The definitions of the length, the data type of the column, the formula, and so on

Chapter 1

How to do it
To provide hibernate mapping based on XML, perform the following steps:
1. Ensure that the basic structure of the configuration file is as follows:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD X.X//EN"
"http://hibernate.sourceforge.net/hibernate-mappingX.X.dtd">
<hibernate-mapping>
...
</hibernate-mapping>

We have not provided the DTD code for the future demo in
this book, but it should be present while developing.

2. Create a XML file and name it Employee.hbm.xml. Then, add the configuration, as
shown in the following code:
<hibernate-mapping>
<class="Employee" table="employee">
<id name="id" type="long" column="id">
<generator class="increment" />
</id>
<property column="firstName" name="firstName" />
<property column="salary" name="salary" />
<!-- other properties mapping-->
</class>
</hibernate-mapping>

Here, we named the mapping file Employee.hbm.xml.


However, while developing, there is no strict rule regarding the
naming convention. Here, we will create a new hbm file for each
POJO; for example, we created an Employee.hbm.xml file for
the Employee.java class. Another common practice we will
use here is to create one hbm file for the module, map all the
classes of this module in the same mapping file, and name this
file modulename.hbm.xml.

How it works
Here, <hibernate-mapping> is a root element that contains all the <class> elements.
The <class> tag contains the following attributes:
f

name: This specifies the FQN (Fully Qualified Name) of the Java class.
9

Setting Up Hibernate
f

table: This denotes the database table used for the class defined in the
name attribute.

The <generator> tag in the <id> tag is used to generate the value of the primary
key. There are many types of built-in generators provided by hibernate, such as
identity, sequence, hilo, and so on.

The <id> tag defines the primary key column for the database table. It contains the
following attributes:
f

name: This specifies the Java class attribute name

column: This denotes the database table's column name

type: This specifies the data type of the column that will help hibernate during the
creation and retrieval of the automatic table

size: This denotes the size attribute that defines the length of the table's column
The type attribute in the <id> and <property> tags helps
hibernate to create a table structure automatically for us using
the hbm mapping.

Usually, we create a mapping file called hbm (hibernate mapping). It is a normal XML schema
file that contains custom hibernate XML tags. This helps the hibernate engine to map the
class to the table and the class field to the table column, along with the given attributes.
All the mapping definitions for hibernate are bundled under the <hibernate-mapping>
... </hibernate-mapping> tag. In <hibernate-mapping> ... </hibernatemapping>, we can add any number of class-to-table mapping definitions.
It is good practice to provide the type in mapping because if
this attribute is not provided, hibernate needs to use reflection
to get the data type of the field; reflection requires a little more
processing than a normal execution does.

There's more
Now, let's create the XML mapping for the POJO having a reference with another POJO. Here,
we will create two different mapping files. To achieve this using an XML-based mapping, we
have to create different class mappings for each POJO that has a dependency.
The following is a code that represents the mapping for the Department class. The mapping
is in the Department.hbm.xml file:

<hibernate-mapping>
10

Chapter 1
<class name="Department" table="department">
<id name="id" type="long" column="id">
<generator class="auto" />
</id>
<property column="deptName" name="deptName" />
<!-- other properties mapping -->
</class>
</hibernate-mapping>

Next, we will create a mapping for the Employee class. Its definition is present in the
Employee.hbm.xml file:

<hibernate-mapping>
<class="Employee" table="employee">
<id name="id" type="long" column="id">
<generator class="auto" />
</id>
<property column="firstName" name="firstName" />
<property column="salary" name="salary" />
<many-to-one name="department" class="Department" >
<column name="department"/>
</many-to-one>
<!-- other properties mapping-->
</class>
</hibernate-mapping>

In the preceding example, we mapped the Department entity with the Employee entity. This
will refer to the department column in the employee table. This means that it will create a
foreign key that is referenced to the department table.
Here, we will use the <many-to-one> relationship, which means that either many employees
are connected with one department, or one department is used by many employees.
The properties are as follows:
f

not-null="true": This property prevents the user from inserting the NULL value
in the column

lazy="true": This feature helps us while retrieving data using hibernate

11

Setting Up Hibernate
The two possible options for lazy are true and false. In our example, Employee is a parent
class, whereas Department is a child of the Employee class. Now, while fetching, if we set
lazy as true, it means that it will only fetch employee records. No child records will be fetched
with Employee, and hibernate will use a separate query if we try to access a child record, which
is employee.getDepartment(). If we set lazy as false, hibernate will fetch the child
records with the parent, which means that the department information will also be fetched,
along with that of the employee. Hibernate will use a join query to fetch the child records.

Providing an annotation-based hibernate


mapping
When we choose the annotation-based way to provide a configuration, we don't need to create
any hibernate mapping (usually *.hbm. xml) file. Hibernate provides the annotations that we
can directly write to the POJO, and we can provide all the mappings via the classes, which we
can do using the previous XML file.

How to do it
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:
1. Represent the annotation-based mapping for the Employee class in
Employee.java, as shown in the following code:
import
import
import
import
import

javax.persistence.Column;
javax.persistence.Entity;
javax.persistence.GeneratedValue;
javax.persistence.Id;
javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name="firstname")
private String firstName;

12

Chapter 1
@Column(name = "salary")
private double salary;
// default constructor
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

How it works
Now, compare the annotations with the XML mapping to gain a better understanding of the
difference between the two methods.

Declaring a class Table for the database


In the annotations, we will write the following code:
@Entity
@Table(name="employee")
public class Employee{...}
13

Setting Up Hibernate
Now, check the XML mapping for the same here:
<class name="Employee" table="employee">

The keywords used in the preceding class are described below:


f

@Entity: This annotation declares the class as an entity bean.

@Table: We can set this annotation at the class level only. You can provide the name

attribute, which is considered as a database table name. You can also just write
@Table without any attribute; in this case, the class name is considered as a table

name by hibernate.

Declaring an ID The primary key for the table


In the annotations, we will write the following code:
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

Now, check the XML mapping for the same in the following code:
<id name="id" type="long" column="id">
<generator class="auto" />
</id>

The annotations used in the preceding code are described below:


f

@Id: This annotation declares the property to be an identifier property, and this is
used as a primary key for the table.

@Column: This annotation is used to define the column for the table. Here, we used
name="id", meaning that hibernate considers the column name to be "id". You
can also write @Column without any attributes; in this case, the property name is

considered to be a column name for the table.


f

@GeneratedValue: Using this annotation, we can provide information to hibernate


on how to generate a value for the primary key column. Here, we will use strategy
= GenerationType.AUTO, which means that hibernate uses the autoincrement
value for the id column. If not provided, hibernate uses the most appropriate
generation strategy.

Referencing an object
In the annotations, we will write the following code:
@JoinColumn(name="department")
@ManyToOne
private Department department;
14

Chapter 1
Now check the XML mapping for the same in the following code:
<many-to-one name="department" class="Department">
<column name="department"/>
</many-to-one>

The annotations used in the preceding code are described below:


f

@JoinColumn: This annotation notifies hibernate that this is a reference column.

@ManyToOne: This annotation defines the relation between the referenced tables.

Here, we have used many-to-one, meaning that one department can be mapped with
multiple employees.

There's more
In the previous section you learned how to reference a class using hibernate. In this section,
we will take a look at how to provide the reference of one class in another class in detail.
Do not get confused when writing Employee.java again to show the reference object
annotation.
The following code represents the annotation-based mapping for the Employee class that
has the reference field in Employee.java:
import
import
import
import
import
import

javax.persistence.Column;
javax.persistence.Entity;
javax.persistence.GeneratedValue;
javax.persistence.Id;
javax.persistence.ManyToOne;
javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name="firstname")
private String firstName;
@Column(name = "salary")
private double salary;
15

Setting Up Hibernate
@JoinColumn(name="department")
@ManyToOne
private Department department;
// default constructor
public Employee() {
}
// getters & setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Department getDepartment(){
return department;
}
public setDepartment(Department department){
this.department = department;
}
}

16

Chapter 1
The following code represents the annotation-based mapping for the Department class in
Department.java:
import
import
import
import
import

javax.persistence.Column;
javax.persistence.Entity;
javax.persistence.GeneratedValue;
javax.persistence.Id;
javax.persistence.Table;

@Entity
@Table //If name is not supplied hibernate will use class name as
table name
public class Department{
@Id
@Column //If name is not supplied hibernate will use field name
as column name
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column
private String deptName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
}

17

Setting Up Hibernate

Providing a hibernate configuration using an


XML file
In the preceding discussion, you learned how to create a class and provide a mapping
to hibernate. These mappings show the relationship between the Java class and the
database table.
Still, hibernate requires some information about the database, host, and port, on which the
application is running. It also requires information about the username and password to
access the database. Hibernate uses this set of configurations to connect to the database.
This is a traditional way to provide the hibernate configuration; however here, we need to create
an XML file, generally called hibernate.cfg.xml, in the classpath. There is no strict rule to
name it hibernate.cfg.xml; we can give it a custom name instead of hibernate.cfg.
xml, in which case, we need to instruct hibernate to load the configuration from the particular
file. Otherwise, hibernate looks for the file named hibernate.cfg.xml in the classpath.

How to do it...
Now, we will create the XML file that shows the configuration for MySQL:
1. Enter the following code in hibernate.cfg.xml to show the configuration for the
applications:
...
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/kode12
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<property name="show_sql">true</property>
18

Chapter 1
<property name="hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping resource="Employee.hbm.xml"/>
<mapping resource="Department.hbm.xml"/>
</session-factory>
</hibernate-configuration>

How it works...
Here, we will take a look at only the basic configuration parameters. Let's understand the
meaning of each property:
f

<property name="hibernate.dialect">org.hibernate.dialect.
MySQLDialect</property>: This property helps hibernate to generate database-

specific SQL statements. This is an optional property. According to hibernate


documentation, hibernate will be able to choose the correct implementation of
dialect automatically using the JDBC metadata returned by the JDBC driver.
f

<property name="hibernate.connection.driver_class">com.mysql.
jdbc.Driver</property>: Using this property, we can provide the Fully Qualified
Name (FQN) of the java driver name for a particular database. The driver class

is implemented using Java and resides in the JAR file and contains the driver that
should be placed in our classpath.
f

<property name="hibernate.connection.url">jdbc:mysql://
localhost:3306/kode12</property>: Using this property, we can provide

the physical location of the database; however, the connection URL may vary from
database to database. Here, we will use the MySQL database, so the URL shows
jdbc:MySQL://<host/computer-name/ip>:<port>/<database name to
connect>.
f

<property name="hibernate.connection.username">root</property>:

Using this property, we can provide the username to access a particular database.
f

<property name="hibernate.connection.password">root</property>:

Using this property, we can provide the password to access a particular database.
f

<property name="show_sql">true</property>: The possible value for this


property is either true or false. This is an optional property. Hibernate logs all the
generated queries that reach the database to the console if the value of show_sql
is set to true. This is useful during basic troubleshooting. Hibernate will use the

prepared statement so that it does not display the parameter in the output window. If
you want to see this parameter as well, you will have to enable the detailed log. Log4j
is preferred for the detailed log.

19

Setting Up Hibernate
f

<property name="hbm2ddl.auto">create</property>: The possible values


are validate, update, create or create-drop. This is also an optional property.
Here, we will set value=create so that it will remove all the schemas and create
a new one using the hibernate mapping on each build of sessionfactory. For
value=update, hibernate will update the new changes in the database.
Do not use the hbm2ddl.auto property in the production
environment because it may remove all of the data and schema.
So, it's best practice to avoid it in the production environment.

<mapping resource="Employee.hbm.xml"/>: All of the mapping file is


declared in the mapping tag, and the mapping file is always named xx.hbm.xml.
We can use multiple mapping tags for multiple mapping files.

Here is an example:
<mapping resource="Employee.hbm.xml"/>
<mapping resource="Department.hbm.xml"/>

There's more
Here are some useful properties used in hibernate:
f

hibernate.format_sql:

The possible values are true and false

It shows the hibernate-generated queries in the pretty format if set as true

hibernate.connection.pool_size:

The possible value is always greater than 1 (value >= 1)

It limits the maximum number of pooled connections

hibernate.connection.autocommit:

The possible values are true and false

It sets the autocommit mode for JDBC

Providing a hibernate configuration using


the properties file
This is another way to configure hibernate; here, we will create a file with the .properties
extension. Usually called hibernate.properties, this file is a replacement for hibernate.
cfg.xml. You can use any approach (either cfg.xml or the properties file). However, the
properties file is better for startup, and it is the easiest approach to get started quickly.
20

Chapter 1
This is a simpler representation of an XML file. Hibernate searches for the XML file or the
properties file at startup to find the configuration in your classpath. We can use any one of
these options. You can use both of them at the same time, but this is uncommon because
hibernate gives priority to the XML file over properties; the properties file is simply ignored in
such cases.
The properties file looks similar to a normal text file, but the content should
be in a key/value pair, which is Key=Value.
Here is an example: hibernate.connection.driver_class=com.
mysql.jdbc.Driver.

How to do it
Now, we will create a file called hibernate.properties in our classpath and write the
following properties in the file. The following code represents hibernate.cfg.xml in the
hibernate.properties file:

hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/kode12
hibernate.connection.username=root
hibernate.connection.password=root
show_sql=true
hbm2ddl.auto=update

How it works
When we create an instance of the Configuration class, it will look for hibernate.cfg.
xml or hibernate.properties in our classpath. If we use a .properties file, it'll get all
of the property defined in the file, rather than create a Configuration object.
The difference between an XML and properties file is that, in an XML
file, you can directly map classes using the <Mapping> tag, but
there is no way to configure it in a properties file. So, you can use
this methodology when you use a programmatic configuration.

21

Setting Up Hibernate

Configuring hibernate programmatically


In the preceding section, we understood XML and the properties-based configuration.
Hibernate also supports the programmatic configuration. To configure hibernate using this
method, we have to work on a Java code and create an instance of the org.hibernate.
cfg.Configuration class. There are multiple ways to configure hibernate.

How to do it
First, write the following code:
Configuration configuration = new Configuration();

This will create an instance of the Configuration class using hibernate.cfg.xml or


hibernate.properties, whichever is found in the classpath.
Provide the following mapping files to the configuration:
configuration = configuration.addResource("Employee.hbm.xml");
configuration = configuration.addResource("Department.hbm.xml");

You can use an alternate way, as shown in the following code:


Configuration configuration = new
Configuration().addResource("Employee.hbm.xml").addResource("Depar
tment.hbm.xml");

We can also provide a direct mapping using the class, as shown in the following code:
configuration = configuration.addClass("Department.class");

This will also look for Department.hbm.xml.


We can also set a custom property. To set up the custom property, use the following method:
configuration.setProperty(propertyName, value);

For example, consider the following code:


configuration.setProperty("show_sql", true);

To set up multiple properties using the properties object, execute the following code:
configuration.setProperties(java.util.Properties properties);

22

Chapter 1
Here is an example:
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.connection.driver_class",
"com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url",
"jdbc:mysql://localhost:3306/kode12");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "root");
properties.put("show_sql", "true");
properties.put("hbm2ddl.auto", "update");
configuration.setProperties(properties);

To read the mapping from the URL, you can use the following code:
configuration = configuration.addURL(java.net.URL url);

To read the mapping from the XML file, you can use the following code:
configuration = configuration.addXML(String xml);

How it works
When we select the programmatic configuration option, the Configuration class
is very important. Using the instance of the Configuration class, we will build a
SessionFactory object, as shown in the following code:
SessionFactory sessionFactory = new
Configuration().buildSessionFactory();

When the preceding code is executed, it creates a SessionFactory object using a


.properties or .cfg file or whichever source is provided to create the configuration.

23

Get more information Java Hibernate Cookbook

Where to buy this book


You can buy Java Hibernate Cookbook from the Packt Publishing website.
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet
book retailers.
Click here for ordering and shipping details.

www.PacktPub.com

Stay Connected:

You might also like