Welcome to the MyEclipse Hibernate and Spring tutorial. This
tutorial is meant to be a quick overview of how using both
Hibernate and Spring in the same project works in MyEclipse.
Before starting this tutorial, we encourage you to start with
first the individual
Introduction to Hibernate and
Introduction to Spring tutorials in the
Resources section that covers the
individual technologies in more detail. The project used in this
tutorial will be similar to the one used in the
Introduction to Hibernate.
The use of Spring with Hibernate will be shown in this tutorial
by creating a layer of abstraction between our persistence code
(Hibernate) and our business logic. The business logic in most
cases will be the "stuff the web application does", for
simplicity sake, in this example it is our
main method. By adding this level of abstraction, we can
use Spring to control the real persistence engine that is plugged
in behind the scenes and used by our business code (main method).
For small applications this may seem inconsequential, but when
you start seeing how easy it is to swap out entire portions of
your code base using Spring by simply adjusting references in
your bean configuration file, it's easy to see how powerful this
tool can become. For the most obvious case, it makes testing much
easier. You are able to say swap in a persistence implementation
that makes all it's calls to an embedded DBMS or maybe logs all
it's activity. Then when the application is deployed to
production, the persistence implementation is switched back to
the code that makes use of the main DBMS and doesn't log anything
for performance reasons.
There are a myriad of possibilities when using Spring.
This tutorial is intended for developers who are somewhat
familiar with either MyEclipse or Eclipse so you are expected to
recognize navigation within the IDE and understand some of the
more common concepts like "Views". Additionally,
developers should be familiar with persistence in Java (JDBC,
EJB, iBatis, JPA, etc.) to be able to understand the role
Hibernate plays more quickly and be familiar with Spring and
dependency injection.
If the reader is unclear on how these individual technologies
work, a much better place to start will be the individual
Hibernate and
Spring tutorials found in the
Resources section
below.
This tutorial was created with MyEclipse 5.1, the bundled
Hibernate 3.1 and Spring 1.2 libraries. If you are using a
another version of MyEclipse, Hibernate or Spring, most of these
screens and instructions should still be very similar.
If you are using a newer version of MyEclipse and notice portions
of this tutorial looking different than the screens you are
seeing, please
let us know and we will make sure to
resolve any inconsistencies.
The project we create during this tutorial, as well as the
create-table SQL script for the database table we used, can be
found in our
Resources section below for those of you
that want to peak ahead. For the rest, we would highly encourage
you to follow along with the tutorial, creating the project as we
go.
To get started with Hibernate and Spring in MyEclipse the first
thing we need is a connection to the database that we want to
build our application to use. In this particular case, it is an
instance of MySQL 5 with a sample
user table we've already created. We are also using the
MySQL Connector/J JDBC driver to connect to our install of MySQL.
So let's get started by creating a new connection, in MyEclipse,
to our database (Note: This is the same project we created in the
Hibernate tutorial as mentioned above):
Figure 1. Creating a connection to
our database
Now that we have a working connection to our database, the second
thing we need before we get started is a Hibernate and
Spring-enabled project (Java, Web, Web Service, etc). We can
create such a project by creating any of the supported types of
base projects, like a Java or Web project, then adding
Hibernate and
Spring capabilities to that project from the
MyEclipse menu, like so:
Figure 2. Creating a Hibernate and
Spring-enabled project
Now that we have a database connection and a project properly
configured, the next thing for us to do is tell MyEclipse to
reverse-engineer our database table into Hibernate (Java) objects
and put them into our project.
In addition to that, because our project is a Hibernate-Spring
project, MyEclipse will give you the option to generate
"Spring DAOs" instead of just plain DAOs during the
reverse engineering. This will automatically create Spring beans
for the DAOs that have their
sessionFactory properties correctly configured to the
existing Spring reference to the Hibernate SessionFactory.
In the example below we use the simplest form of
reverse-engineering, letting the wizard take all the default
values. However, for maximum control you could optionally
use the
Next button and step through the wizard to select
details like primary key generation strategy, object names, types
and more. Let's reverse-engineer our table now:
Figure 3. Reverse-engineering our
user table into Hibernate (Java) objects
Now that we have our project setup we are ready to start writing
some code. There are going to be two pieces of code we write:
Business Logic: Our
main method that represents the code we actually write
for our applications.
Persistence Layer: This is the abstracted portion of our
application that our business logic relies on for database
functions. If all our business logic ever uses is the
persistence layer, that allows us to hide some of the details of
how it all works behind this layer. We are going to use Spring
to populate our persistence layer with the necessary DAO
reference it needs to
actually perform the database operations, but the
benefit here is that our business logic doesn't need to know
anything about that.
Let's first start with the persistence layer since that is what
sits between all the code we just generated and the code we will
write in the business logic layer. The code for our
PersistenceLayer class will look like this:
package com.myeclipse.hibernatespring;
public class PersistenceLayer {
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public void addUser(User user) {
userDAO.save(user);
}
public User findUserById(Integer id) {
return
userDAO.findById(id);
}
public void updateUser(User user) {
userDAO.merge(user);
}
public void deleteUser(User user) {
userDAO.delete(user);
}
}
Figure 4. Implementation of our
PersistenceLayer class
The code is fairly straight forward, but let's recap. The
purpose of this class is to get a
UserDAO instance injected into it by Spring and then it
uses that reference under the covers to actually implement the
save/find/update and delete operations without the calling code's
knowledge. This allows us to easily and quickly modify the
persistence code in the application without changing the
application code at all. More specifically, if we ever wanted to
change how PersistenceLayer was implemented, say to manage
exceptions better, transactions or anything else, we could simply
edit this class and be done, there would be no need to refactor
the entire application as long as all the method signatures
stayed the same.
The other important thing to note is that since this layer of
abstraction is loosely coupled with the persistence code from the
application code, it's easy for us to use Spring to inject say a
testing
UserDAO implementation that simulates DB operations but
doesn't actually perform them. There are all sorts of advantages
to this design.
Now that we have
PersistenceLayer implemented, let's take a look at the
business logic (or our
main method implementation):
package com.myeclipse.hibernatespring;
public class BusinessLogic {
public static void main(String[] args) {
/* 1. Create a new user */
Integer id = new
Integer(1);
User user = new User();
user.setId(id);
user.setUsername("jdoe");
user.setPassword("1234");
user.setFirstName("John");
user.setLastName("Doe");
user.setDateCreated(Long.valueOf(System.currentTimeMillis()));
/* 2. Load the Spring bean configuration and
create a bean factory */
BeanFactory beanFactory
= new XmlBeanFactory(new ClassPathResource(
"applicationContext.xml"));
/* 4. Save the new user to the database */
persistenceLayer.addUser(user);
/* 5. Confirm that our user was saved */
User userLoadedFromDB =
persistenceLayer.findUserById(id);
System.out.println("User Loaded from DB [username="
+ userLoadedFromDB.getUsername() + ",
password="
+ userLoadedFromDB.getPassword() + ",
firstName="
+ userLoadedFromDB.getFirstName() + ",
lastName="
+ userLoadedFromDB.getLastName() +
"]");
/* 6. Update the user */
userLoadedFromDB.setFirstName("Johnathan");
persistenceLayer.updateUser(userLoadedFromDB);
/* 7. Confirm that the update worked */
User
userLoadedFromDBAgain = persistenceLayer
.findUserById(id);
System.out.println("User Loaded from DB Again
[firstName="
+ userLoadedFromDBAgain.getFirstName() +
"]");
/* 8. Delete the user */
persistenceLayer.deleteUser(user);
}
}
Figure 5. Implementation of our
business logic (main) class
Let's take a quick look at what this code is doing:
Create a new user to insert into the database. This is just a
POJO, nothing interesting. We are using the
User POJO that MyEclipse generated for us when we
reverse-engineered the
user table from the database.
Create a bean factory. What this does is read in the Spring bean
configuration file and then provide you an instance to a
"factory" that can be used to get instances of beans
based on the specification from that file. This is the Spring
"entry point" as it were.
Create an instance of
PersistenceLayer so we can perform DB operations.
Notice how we have to use the bean factory to get the instance
in order to have the
UserDAO reference populated correctly.
Save the new user to the DB using the
PersistenceLayer instance we created. Notice how the
BusinessLogic class has no knowledge of the
UserDAO class or any underlying details because all the
calls are going through the
PersistenceLayer
Now we actually reload the user from the database using the ID
that was assigned to it when it was saved and check to make sure
all the values are right.
Now let's update the user name to see if updating records will
work.
We reload the user from the database
again to make sure that the updated change we made
stuck.
Delete the user from the DB.
Some of you might be asking yourself: "
How does the PersistenceLayer get a reference to UserDAO
in order to actually execute those persistence operations? I
don't see that code anywhere." and the answer to that is:
We need to create a new Spring bean (PersistenceLayer) that will
get the correct
UserDAO instance injected into it at runtime so the code
will run correctly. Doing that looks something like this:
Figure 6. Creating the persistenceLayer
Spring bean that our business logic will use
Now our application should be ready to run, let's recap the major
portions of what we have done:
Reverse-engineered our database using MyEclipse and Hibernate
Wrote a layer of abstraction between our persistence technology
(Hibernate) and our business logic (main method) that will be
managed by Spring.
Write our business logic (main method) to make use of the
abstracted persistence layer to add/find/update and delete a
user from the database.
Created a new Spring bean configuration entry for our abstracted
persistence layer so it gets the correct reference to the DAO
generated by MyEclipse automatically in order to communicate
with the DB.
Now we can actually run our
BusinessLogic class and see our application in action:
Figure 7. Running our example
business logic code
Very nice, it worked correctly just as we had hoped! We can see
we were able to store, update and delete our user from the
database with just a few lines of code. Imagine how easy writing
the rest of this application will be since all we need to do is
use our
PersistenceLayer.
MyEclipse 6.5 introduces Hibernate Annotations support for both standalone Hibernate projects and for Spring Hibernate projects.
The following section presents a brief overview of our support for Hibernate Annotations and Spring.
Creating a Hibernate Spring project with Annotations Support
Follow the steps in Figure 2 above to create a Hibernate and
Spring enabled project. The following changes are necessary to
enable annotation support.
When adding Hibernate capabilities, to your project, be sure to
use Hibernate 3.2 and select
Enable Hibernate Annotations Support.
Figure 8. Adding Hibernate capabilities with Annotations support
When adding Spring capabilities on page 3, select
Enable Hibernate Annotations support. This will create
an
AnnotationSessionFactoryBean instead of a
LocalSessionFactoryBean, the former is required when working
with annotations.
Figure 9. Adding Spring capabilities with Annotations support
Figure 10. AnnotationSessionFactoryBean generated by the Spring capabilities wizard
Reverse Engineering
The Hibernate project properties page in a project setup using
the above process will list both LocalSessionFactoryBean beans
as well as AnnotationSessionFactoryBean beans in the
SessionFactory Bean Id combo when you select a Spring
beans configuration file.
For annotations support during reverse engineering, you must either select a
Hibernate configuration file as your Active configuration file or
a Spring beans configuration file and an AnnotationSessionFactoryBean
for the SessionFactory.
Figure 11. Hibernate project property page
The session factory beans Ids presented for Spring DAOs will
depend on whether you've chosen to generate annotated POJOs or
Hibernate mapping files. If you chose to generate annotated
POJOs, then only AnnotationSessionFactoryBeans are presented in
the
SessionFactory Id combo, else both
LocalSessionFactoryBean beans and AnnotationSessionFactoryBean
beans are listed.
Other aspects of our Hibernate Annotations and Spring support are no different from
what has already been covered in the earlier sections of this tutorial.
As was shown in the Introduction to Hibernate and Introduction to Spring tutorials (see Resources) working with these technologies in MyEclipse is very straight forward and easy. What we tried to show in this tutorial was not only why using these technologies together is a good idea, but how MyEclipse will even help you develop using the technologies in the same project.
We hope you have found this tutorial helpful. If you had comments
about this tutorial or suggestions/questions for us, please
let us know. We always value our user's
feedback especially on educational materials such as these.
Below are links to resources that we hope will help answer most
of the questions you could have while working your way through
this tutorial pertaining to Hibernate:
We would like to hear from you! If you liked this tutorial, has
some suggestions or even some corrections for us please let us
know. We track all user feedback about our learning material in
our
Documentation Forum.
Please be sure to let us know which piece of MyEclipse material
you are commenting on so we can quickly pinpoint any issues that
arise.