How do you get
started with Hibernate?
When I write about technology, I like to assume the reader
already has their environment set up and ready to go. For example, in
my portlet programming book, I jump right into the code, expecting
that if someone is reading a book on portlets, they've already got
some type of development tool set up to help facilitate their coding.
Unfortunately, I just don't feel comfortable doing that with
Hibernate. So, we're going to jump into a little discussion about all
of the things you need to download and configure in order to work
through the various examples on this site. Don't worry, there's not
too much to do. You do need a database, you do need a Java
compiler, and you will need to download some files from Hibernate.org, but in the grand
scheme of things, it's not really a back-breaking amount of work.
So, without any further ado, here's what you need in order to
start working with Hibernate and JPA annotations:
- A JDBC compliant Database. (and the ability to perform the
most basic of database administration tasks.) You can't do Java
persistence without a database!!!
- The JDK 1.5 or better, as annotations didn't exist before
Java 5 (JDK 1.5 == Java 5. Why? Don't ask!)
- JDBC Drivers for your Database -that's how Hibernate
connects to your database of choice
- The various jar files and libraries associated with the
Hibernate Core and Hibernate Annotations (essentially, you need
Hibernate)
- A properly configured hibernate.cfg.xml file on your runtime
classpath.(Don't worry, we'll work on that together when the time
comes)
Step 1: Get a Database!!!
Hibernate is all about persisting the state of your Java
components to a database. That's what Hibernate does; it helps Java
programmers, in a very natural and object-oriented way, persist their
data to a database. And if you want to persist data to a database,
well, you obviously need a database.
Now, I don't really care which database you install. Hibernate
is database agnostic, and very egalitarian in the fact that it really
doesn't care which database you use, so long as your database is JDBC
compliant. For the examples in these tutorials, I'm going to use MySQL
as the database of choice. You can use DB2, Oracle, Sybase, or any
other JDBC compliant database that you like, but for me, I'm going to
use MySQL. Why MySQL, you ask? Well, because MySQL is free, and that's
a price I don't mind paying. Plus, the installation is a snap, and it
comes with some pretty sweet GUI tools for doing basic database
administration. If you're not committed to any particular database,
MySQL really isn't all that expensive of a download.
My Three Favorite MySQL Components
From mysql.org, I downloaded
three key components, namely:
As far as installation goes, with MySQL, it's more of an
unzipping of files than anything else. I just unzip the database
related files into a folder named C:\_mysql, and I unzip the MySQL GUI
tools into a folder named C:\_mysql gui tools, and voila, MySQL and
its complimentary GUI tools are installed.
|
You'll notice that whenever I create folders, I
typically create them with a leading underscore, _. I do it for two
reasons:
- 1. It annoys the hell out of my fellow developers
who have to share folders with me or work on my computer. :)
- 2. It puts all of my important folders right at
the top of the File Explorer hierarchy, making things easier to
find, and I like looking for things that are easy to find.
|
Gentlemen...start Your Database...
Before you can do anything interesting with a database, you
need to start it. To start MySQL for example, I just jump in the bin
directory and run the mysql-nt.exe --console command. Obviously, this
is on a Windows XP machine, and dare I say it again, for a MySQL
installation. Each database and operating system will have its own
unique startup command. If starting up your locally installed database
is a mystery, ask for some help from a friend, co-worker or mentor.
This is no time to be too proud to recruit some experienced help - if
you can't get a database started, you won't be very successful in the
world of database persistence.
| C:\_mysql\bin>mysqld-nt.exe
--console InnoDB: Starting crash recovery.... InnoDB: Reading
tablespace information from files... InnoDB: Restoring possible
half-written data pages InnoDB: buffer...... 080103 7:42:57 InnoDB:
Starting log scan ... InnoDB: log sequence number 0 46441....
080103 7:42:57 InnoDB: Started; log sequence number 0 46441...
7:42:59 [Note] mysqld-nt.exe: ready for connections.... Version:
'5.0.45-community-nt' socket: '' port: 3306 MySQL Community Edition
(GPL)... |
Please, Make This a True Assumption
As I go through this tutorial, and prepare to introduce you to
the marvelous world of Hibernate, I have assumed that you have
successfully installed a database, any database of your liking,
and have a basic, fundamental idea about how to use it. I like MySQL,
but you can use any JDBC compliant database that you want;
unfortunately though, I can't give detailed descriptions on how to
install and configure every single database in the world. :( There are
just too many databases out there for me to describe how to install
and configure each and every one. However, on a brighter note, once we
jump into the world of Hibernate, there really isn't that much
database specific configuration that needs to be done, as Hibernate is
database agnostic.
The Shortcomings of Hibernate
Hibernate is pretty amazing, and you'll be astonished at how
many neat things it can do when it comes to managing database tables,
manipulating data, and persisting the state of your JavaBeans.
However, as amazing as Hibernate is, there are certain things that it
just can't do. Here's a brief list of some of Hibernate's biggest
shortcomings:
- It won't grab you a Tim
Hortons coffee in the morning
- It won't stop you from making a dumb, drunk phone call to
your ex-girlfriend
- It can't create a database schema for you
Now, all said and done, I think we can learn to live with these
three shortcomings. I have my own ways of dealing with the first two,
but the third is the one I'd like to deal with right now, namely, the
creation of a database schema named examscam.
What the Heck is a Schema?
What is a database schema? Well, a schema is where a common set
of database tables reside.Think of it as a form of logical
partitioning of application related tables within a database.
Different databases may have different colloquialisms for the
idea o f a schema, but regardless of what it's called, you
need a recognizable schema in your database in order for Hibernate to
know of which collection of database tables to connect.
A database schema named examscam is the umbrella
under which all of the tables that we will use in this book will be
created and maintained. The schema name examscam will be
referenced quite a few times throughout this book, and it will also be
written in a configuration file or two. If you don't like the schema
name of examscam, and you decide to give your schema a
clever little name of your own, just be forewarned that the clever
little name you choose will need to be injected into a variety of
config files. If you're new to Hibernate, and you want to be safe,
just humor me and use the same schema name. I assure you, life, and
troubleshooting, will be easier.
Quickly Creating a Database Schema
inMySQL
Using the MySQL Query Browser GUI Tool, creating a new schema
is just two or three simple steps. Each database is different though,
and if you're having trouble with yours, you may need to go to the
reference material for your database of choice. Or better yet, ask
someone in the know, or even post a query on a message board such as
the Big Moose Saloon at JavaRanch.com.
(I tend to hang out at the ranch quite a bit. )
The Create Schema SQL Command
So, database tables must be contained within a schema
(schemata? Catalog?). The following is your standard SQL for creating
a database schema named examscam, just in case you're one of those
freakish people that gets off on command line executions, as opposed
to using those girly-man GUI tools.
CREATE DATABASE `examscam`;
Knowing the Database Basics
I know I've said it before, but I want to say it again: I do
apologize for not taking you through every piece of minutia with
regards to creating a database, and setting up database tables. I
mean, I'll always try to provide the SQL required to manipulate a
database, but how to execute the provided SQL against your particular
database, and how to issue commands against your database is a little
bit outside of the scope of this book.
If you're new to using a database like MySQL, or Oracle, or
DB2, and you're not comfortable with issuing SQL statements or using
the GUI tools that accompany your database, reach out to someone on
your team, or someone you know, and get some assistance. Programming
is tough enough without having to struggle with getting the basic
database schema set up.
Step 2: Installing the JDK'version 1.5
or Higher
In order to write and run Java code, you need a compiler and a
runtime environment. You can get all of that from Sun Microsystems by simply
downloading the JDK, aka the Java Development toolKit.
In order to use Hibernate with JPA annotations, you need to
have a Java 5 environment or higher, which means your JDK must be at
version 1.5 or better. Yes, I know it's called Java 5, but if you look
under the covers, it's really a 1.5 version of the runtime
environment. I guess Java 5 just sounded kewler to the people at Sun,
so that's what they call it; but don't be fooled, as a Java 5 JRE is
really at a JDK version level of 1.5.
For the most part, I use Java 1.6 for the examples in this
tutorial, but anything from version Java 5 and onwards will do just
fine.
And a note about downloading the JDK: there are all sorts of
Java environments out there, including the Enterprise Environment, a
Micro Environment, and a Standard Edition Environment. Since we just
want a basic Java runtime, the Java SE, or Standard Edition, or the
Standard Development Kit (SDK), is what you want to download and
install.
JavaSoft
Downloads
Finding the JDK on Sun's Site
In order to get your fingers on the JDK, you have to go to Sun
Microsystems's website, at http://java.sun.com, or even
http://www.javasoft.com. Both urls pretty much take you to the same
place. There's usually a link on the landing page called Popular
Downloads, which will probably change as soon as I finish writing
this, but nevertheless, there should be a link on Sun's site that
allows you to download Java SE, the Standard Edition. Java SE is what
you want.
Now, when you go to the downloads page, you'll see all sorts of
links to download JDK 6, or JDK 6u1, or something like that. Java 6
will do just fine, but so will Java 5. If you want Java 5, you'll have
to find a link on the page that says Previous Releases or something
like that. Regardless, you need a Java 5 SE JDK or better to work with
Hibernate and JPA annotations, so head over to www.javasoft.com and
dig around until you find a link for J2SE Downloads or something
similar.
Installing the SE JDK, 1.5 or Higher
Now, when you install the JDK, the installer will ask for an
installation directory. On Windows, this usually defaults to
C:\Program Files\jdk1.6.0x.x or something crazy like that. I hate
that.
Personally, I recommend you install the JDK into a folder right
off the root of C:\, preferably C:\_jdk1.5 if you're using Java 5, or
C:\_jdk1.6 if you're using Java 6. I like to have the underscore in
there as well, because it puts the JDK right near the top of the
folders list when you open up the file system explorer. After I've
been working on a computer for a while, there'll be a whole whack of
folders branching off the root of C:\ with leading underscores. Those
will all be mine. :)
Using a Proper Development Environment
Now, for this chapter, I'm going to demonstrate the most basic,
bare bones environment that is needed in order for you to get
Hibernate working and configured properly. To do that, I'm going to
assume you have nothing more than the JDK and a text editor to create,
compile, and run some Java code. But for God's sake, get yourself a
proper development environment for writing code. Eclipse is a free Java development
environment, and I hear good things about NetBeans as well. Once you
start doing some heavy coding with Java and Hibernate, you should be
working within a proper, rapid application development environment. It
will make your life easier, help you learn Hibernate faster, and allow
you to maintain what is left of your sanity for just a little while
longer.
Step 3: Add the JDBC Drivers to the
Classpath
You can install a Java Runtime Environment (JRE), and you can
install a database, and you can code all of the Hibernate or JPA or
Java code that you want, but that doesn't help your Java runtime
environment connect to your database. In order for a Java program to
connect to a database, the Java environment needs access to the
appropriate JDBC drivers. JDBC drivers are used by a Java program to
connect to the database of interest.
Since every database in the world is different, every database
has its own special set of JDBC drivers. For example, after installing
MySQL on my own computer, I had to go to mysql.org and download the
Connector/J, MySQL JDBC drivers, which were distributed in a jar file
named mysql-connector-java-5.0.8-bin.jar. This file then needed to be
added to the classpath of my Java environment. The last time I
checked, DB2 had all of its JDBC drivers packaged in a jar file named
db2java.zip. I'm not sure about Oracle or Sybase. The point it, every
database has its own special set of JDBC drivers, and it is your
job to find them, download them, and add them to your classpath.
Since every database is different, I can't possibly describe
all the various database drivers that might be required to make your
Java environment connect to your particular database. If you're on
shaky ground when it comes to figuring out which database drivers you
need to use, and where to get those database drivers, ask a friend,
solicit help from someone on your development team, or even post a
question for help in JavaRanch's Big Moose Saloon (www.javaranch.com).
Don't waste too much time fighting battles over where to find your
database's JDBC drivers. They're out there - go find them!
An Extra Nugget or Two of Information
Now, when your Java application uses JDBC drivers to connect to
a database, it needs a couple of very important pieces of information,
namely the specific class name of the JDBC driver that will be
contained in the JDBC driver archive file (zip or jar), as well as the
syntax of the connection URL.
For MySQL, the connection URL and JDBC driver class name looks
like this:
For MySQL:
JDBC Driver Name: com.mysql.jdbc.Driver
Connection URL: jdbc:mysql://localhost/examscam
We don't need to configure these values right now, but it is
worth mentioning right now that these values are required, as you
usually find these values referenced time and time again in the same
place that you download your JDBC drivers.
The JDBC driver name will be a fully qualified class name that
is actually contained within your JDBC driver archive file.
The connection URL can actually get pretty bizarre. The big
thing to note is that the connection URL will contain the name of the
database schema you are using, which in this case, is examscam. If
you're asking someone what your specific connection URL should be, you
should phrase it something like this: "given a database schema named
examscam, and my specific database, what would be the syntax of the
connection URL."
Try to figure out these two properties for your specific
database, given a db schema named examscam, and write them down.
JDBC Driver for MY database:
__________________________________________________
Connection URL for MY database:
__________________________________________________
Put Your JDBC Drivers on you
Classpath!!!
Once you've got your JDBC drivers downloaded and on your
workstation, you've got to put them somewhere that your Java runtime
can find them. I'm creating a folder named _hiblib, right off the root
of C:\ on my hard drive (C:\_hiblib, yes, that's an underscore) , and
I'm going to place all of my required libraries, such as the hibernate
libraries and JDBC drivers, right into this _hiblib folder. Then, when
I run my complier or kick off my runtime environment, this folder will
be referenced.
The key is that the JDBC drivers must be on the classpath so
your Java environment can find them. I'm going to keep things as basic
and as egalitarian as possible in my examples, simply using the JDK
and the javac compiler to compile my code. Alternatively, if you're
developing within a Servlet and JSP environment, you might put the
JDBC drivers in the lib folder of the web module. For that matter, if
you're working in a production environment, you may actually have the
JDBC drivers on the application server's external classpath, so
instead of packaging the JDBC drivers in the lib directory of an EJB
module or WAR file, you might just link to them as external JAR files,
resting securely on the knowledge that you'll be able to link to them
at runtime.
How you package your application isn't the biggest concern
right now. Right now, the biggest concern is that your Java
environment can find your JDBC drivers when Hibernate needs them.
Step 3: Get the Hibernate Libraries
Do you know what this book is called? Well, actually, as I
write this, I don't know what it will actually be called when it goes
to press, but I'm sure the title will be something about doing Data
Persistence with Hibernate and JPA Annotations. Given such a title, it
shouldn't surprise you to find out that you're going to need to head
over to hibernate.org and download a couple of Hibernate modules, and
then add the various libraries that are a part of those modules to
the classpath.
For older versions of Hibernate that used the very unsexy XML
mapping files, all you needed to download to get things working was
the Hibernate Core. Indeed, we still need to download the Hibernate
Core module from hibernate.org, but since we don't want to mess around
with XML mapping files in our applications, --- we want to use
annotations --- we need to download an additional Hibernate module,
namely the aptly monikered Hibernate Annotations module. The Hibernate
Annotations module will give us access to the very kewl JPA
annotations that make life so much easier than previous editions of
Hibernate that required hours of editing of tedious XML files.
The following versions of the Hibernate Core and Hibernate
Annotations were used for this book:
Hibernate Core 3.2.5.ga 31.07.2007
Hibernate Annotations 3.3.0 GA 20.03.2007
VERY IMPORTANT NOTE!!!
The examples in this book require you to download the Hibernate
Core package, and the Hibernate Annotations module as well, from
www.hibernate.org
YOU MUST DOWNLOAD THE HIBERNATE CORE
YOU MUST DOWNLOAD HIBERNATE ANNOTATIONS
You must also have a jar file
containing your JDBC Drivers.
The downloaded contents must be extracted to your file system,
and all of the jar files contained within that extracted download must
be made available to your Java development environment, as well as
your Java runtime environment. Adding the contained jar files to the
Java CLASSPATH typically does the trick.
Linking to the Hibernate Jar Files
After downloading and extracting the Hibernate Core module, you
will be presented with quite an elaborate directory structure,
involving folders named doc, etc, lib and src.
As you can probably guess, the doc folder contains a wealth of
information, including JavaDoc for the entire set of Hibernate core
libraries. For specific information about a given Hibernate component
and method, the JavaDoc is the right place to look.
Tutorials and Sample XML Files
The doc folder also contains a tutorial folder, with some
sample XML files, namely a sample hibernate.cfg.xml file and some
sample hbm.xml files.
These files are very fussy about syntax and grammar, so when it
comes time to write your own, sometimes borrowing from these sample
files is a very good idea.
The All Important \lib Directory
For us right now, the most important folder in the Hibernate
Core download is the lib directory. This lib directory contains most
(note most, not all) of the various jar files needed for running Core
Hibernate applications. I really don't care how you do it, but you
have to make sure these files are on the CLASSPATH of your JVM.
If you're coding a web based application, you can happily shove
these jar files into the WEB-INF\lib directory. If you are running
your code directly from the JDK, you can reference this folder using a
CLASSPATH switch; heck, you could even throw these files in the
JDK\lib directory if you really wanted, although that would be a
pretty heavy hammer to drop. The key point is, you need to be able to
link to these jar files at both compile time and runtime. For me, I'm
adding them all to the C:\_hiblib folder in which I also added my JDBC
drivers. I will then reference this folder when I both compile and run
my Hibernate code.
The Hibernate framework requires quite a sizeable number of jar
files to be available to the JVM at both compile time and runtime.
Make sure these Hibernate Core jar files, along with the jar files
from the Hibernate Annotations module, are added to the classpath!
Get the Core Hibernate File
hibernate3.jar
Curiously, out of all of the files contained within the lib
directory of the Hibernate Core module download, none of those files
actually contain the Core Hibernate API. Bizarre, isn't it?
All of the files in the lib directory of the Hibernate Core
download are required files that the Hibernate API needs to link to at
runtime. However, the actual byte-code embodiment of the Hibernate
Core API is contained within a file named hibernate3.jar, and that
file just happens to be floating around right there in the root of the
Hibernate Core download. Look for it right there in the base folder,
with the folder itself likely being named something like
\hibernate-3.2.
Add the hibernate3.jar File to Your
Classpath
Again, the core Hibernate API files are in the hibernate3.jar
file, so this file must be on the classpath of your runtime and
compile time environments. As with the JDBC driver JAR file for your
database, and the numerous JAR files that were in the Core Hibernate
download's \lib directory, I'm going to copy the hibernate3.jar file
into the C:\_hiblib directory. If you're following along, I suggest
you copy the hibernate3.jar file in there as well. However, regardless
of where you put it, make sure it's on the classpath of both your
runtime and compile time Java environments.
Getting the Hibernate Annotations
Module
I sure hope you enjoyed the various steps associated with
getting access to all of the Hibernate Core libraries, because you're
going to have to follow pretty much the same steps to acquire the
libraries associated with the Hibernate Annotations module.
There are three JAR files contained within the Hibernate
Annotations module download that must be added to your classpath,
namely (I bet you'll miss one of them):
- ejb3-persistence.jar
- hibernate-commons-annotations.jar
- hibernate-annotations.jar
Just to keep you off guard, these three JAR files are contained
in two different folders of the Hibernate Annotations module download.
The \lib directory of the downloaded Hibernate Annotations module
contains the *commons* and *annotations* jar files, whereas the
ejb3-persistence.jar file is in the root folder of the download, with
that root folder most likely being named
hibernate-annotations-3.3.0.GA or something creative like that; at
least mine was.
So, take the two JAR files in the \lib directory of the
Hibernate Annotations module and throw them in your C:\_hiblib folder,
or, for that matter, any folder that will make these JAR files
available to both your Java compile time and Java runtime
environments. I've put all my JDBC drivers and Hibernate Core
libraries in the C:\_hiblib directory, so I'm going to do the same
with the JAR files associated with Hibernate Annotations.
hibernate-annotations.jar
As was mentioned, you need to add three JAR files to your
classpath in order to use Hibernate with JPA annotations, with those
three JAR files being:
- ejb3-persistence.jar,
- hibernate-commons-annotations.jar
- hibernate-annotations.jar
The two JAR files that start with the name hibernate are found
in the \lib directory of the Hibernate Annotations download, while the
third, the ejb3-persistence.jar file, is found in the root folder of
the Hibernate Annotations download. This JAR file needs to be added to
your classpath, otherwise you'll run into all sorts of linking and
ClassNotFoundExceptions.
For me, all of the JAR files my application needs are getting
placed in the C:\_hiblib directory, which I will reference when I
compile and run my code. This is where I'm placing the
ejb3-persistence.jar file.
A Hasty Mistake
By this point, people who are new to Hibernate are getting a
little anxious and unruly, as they want to get their environment
configured so they can start hacking out some code. Quite often, due
to overanxious haste, only one or two of these three required JAR
files makes it onto the classpath, causing frustrating errors down the
road. Do a double-check, making sure you have added all of the
required JAR files to your classpath.
A Look at my Hibernate & JDBC
Libraries
After getting my JDBC drivers, Hibernate Core and Hibernate
Annotations related JAR files, my C:\_hiblib folder, which I'll make
sure is available to my Java compile and runtime environments, looks
like this:
Configuring the hibernate.cfg.xml File
Now, there is one last piece of the puzzle that we must put in
place before we can start coding our Hibernate applications and
watching the Hibernate framework persist the state of our JavaBeans to
the database. That last piece of the puzzle is the appropriate editing
and saving of the hibernate.cfg.xml file, which is a special
configuration file that tells hibernate where our database is, what
database driver to use to connect to our database, what the connection
URL is, and any username and password credentials that might be needed
to create an authenticated database connection.
Get a Sample hibernate.cfg.xml File!!!
I hate writing XML, especially when I don't have any XML
validators checking my syntax and structure as I type. The
hibernate.cfg.xml file is a pretty big XML file at the best of times,
and trying to write the whole darned thing out by hand is just silly.
If you need one, the best thing to do is to get a sample
hibernate.cfg.xml file and edit it to suit your particular
installation.
If you downloaded the Hibernate Core module, you'd be able to
find a tutorial with an src folder in it. This src folder contains a
hibernate.cfg.xml file that is used for the sample Hibernate
application that comes with the download. Use this XML file as a template,
and make the changes required to suit your own environment.
Looking at the hibernate.cfg.xml File
Here's how my hibernate.cfg.xml file is going to look when I
get it all edited. As you can see, it's far too much for a ludite like
myself to correctly type out by hand.
<?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="connection.url">
jdbc:mysql://localhost/examscam
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
password
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name="current_session_context_class">
thread
</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">
true
</property>
<!-- mapping files NOTICE WE HAVE NONE-->
</session-factory>
</hibernate-configuration>
Editing YOUR hibernate.cfg.xml File
Properly editing your hibernate.cfg.xml file is a pretty
important step; after all, if you mess up here, your Java applications
will fail when Hibernate tries to connect to your database.
I've tried to prepare you for this next step, as when I
talked about downloading the JDBC drivers for your database, I
mentioned that it was a good idea to figure out what the connection
url and driver name was for your particular database. With this
information in hand, you must edit your hibernate.cfg.xml file to look
like mine, with the key differences being that you must provide the
username and password for connecting to YOUR database, along with the
connection.url and connection.driver_class property that is
appropriate for you. Furthermore, you will need to add a dialect entry
for your specific database.
For MySQL, the dialect is set to
org.hibernate.dialect.MySQLDialect, which is actually a Java class
that comes with the Hibernate Core download. If you are using a
database other than MySQL, you'll have to check the documentation to
find the dialect class specific to your database, and make the
appropriate change in the hibernate.cfg.xml file.
Where do you put the hibernate.cfg.xml
file???
Of course, if you're customizing the sample hibernate.cfg.xml
file that comes with the Hibernate Core download, you'll have to save
the edited file to a more conspicuous place on your workstation. The
only rule about the hibernate.cfg.xml file is that it must be on your
classpath. I typically place it in the src directory where I write my
Java code, and make sure it gets copied into the build folder where my
compiled byte-code gets placed. In this instance, I'm just going to
save the hibernate.cfg.xml file in the C:\_hiblib folder, and make
sure this folder is on the classpath whenever I compile or run my Java
code.
Important Properties of the
hibernate.cfg.xml
You'd be amazed at the number of configurable properties that
you can define in the hibernate.cfg.xml file. It's worth looking at
the documentation that comes with Hibernate to see all of the
different settings that are possible. My goal here is not to bore you
to death by regurgitating the contents of a Hibernate reference
manual, so I'm not going to bore you with details about every possible
configuration setting. However, here is a little bit more detail about
the minimum configuration settings that should exist in any
hibernate.cfg.xml file.
connection.url: this is simply the standard url that any Java
application would use to connect to the database of choice. For
connecting to a MySQL database on the local machine, with a schema
name of examscam, the url would be:
jdbc:mysql://localhost/examscam
However, it should be noted that each database is different,
and the URL syntax is dependent upon both the database, the schema
name, and the database driver being used.
connection.driver_class: a database specific setting, this
setting defines the database driver, in the form of a Java class file,
used by Hibernate to connect to the database. It should be mentioned
that the class file you specify as the driver_class must actually be
on the CLASSPATH, or Hibernate will not be able to find it at runtime.
connection.username and connection.password: somewhat
self-explanatory, you typically need to provide the username and
password used for connecting to your database.
dialect: despite all of the best efforts at standardization,
every database behaves differently. To try and iron out the various
nuances between all of the different databases, Hibernate defines
database specific dialects. For MySQL, we use :
org.hibernate.dialect.MySQLDialect
transaction.factory_class: this is used to specify the class
implementing the TransactionFactory interface. For me, I use:
org.hibernate.transaction.JDBCTransactionFactory
hibernate.show_sql: this will instruct Hibernate to output the
SQL code used whenever it interacts with the database. This is very
helpful for both learning how Hibernate works, and when trying to
diagnose bugs and problems.
Once you have your hibernate.cfg.xml file configured properly,
make sure it is saved in a spot where your Java compiler and runtime
environment can find it. Without this configuration file, your Java
applications will not be able to connect to the database using the
Hibernate framework.
My Complete hibernate.cfg.xml File (Again)
<?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="connection.url">
jdbc:mysql://localhost/examscam
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
password
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name="current_session_context_class">
thread
</property>
<!-- this will show us all sql statements -->
<property name="hibernate.show_sql">
true
</property>
<!-- mapping files NOTICE WE HAVE NONE-->
</session-factory>
</hibernate-configuration>
And that's it!
So, that's it. I guess it's a bit of work getting all of the various
class files that are required to make Hibernate work, and of course,
there's a bit of work involved in installing and configuring a
database, but I assure you, it's all worth it. Having the Hibernate
framework at our fingertips is going to make Java programs that
persist data to a database so much easier to write.
And just to review, what were the steps we took to get our environment
configured? Well, there were really five, important, top level steps,
namely:
- Installing a JDBC compliant Database
- Obtaining JDBC Drivers for the Database
- Getting the various jar files and libraries associated with
the Core Hibernate and Hibernate Annotations modules
- Installing the JDK, version 1.5 or sexier
- Appropriately editing and saving a hibernate.cfg.xml file
So, what's next?
What's next, you ask? Well, if you think everything is
configured, it's time to test to see if it's configured correctly. The
next tutorial will have you write some kewl Java code that uses
Hibernate and JPA Annotations to connect to the database and create
some supporting database tables. If it works, everything is configured
properly, and we can then dive head first into that empty pool known
as database persistence.
|