Reference - DZONE
In this tutorial, you will see how to integrate Spring and Hibernate. I assume you are comfortable with both. At the end of this example, you will learn to create a form through which you can add a user and list all the existing users, as shown below.
Here is the directory structure of the example.
You need to have the following lib files in the WEB-INF/lib directory.
The most important part of the example is the spring bean configuration. Here is the spring bean configuration file.
Here, we use the Jakarta Commons DBCP BasicDataSource to set up a JDBC DataSource. I am using hsqldb database here. If you are using MySQL, then you need to change this configuration.
Hibernate SessionFactory can be configured in the spring bean configuration file itself, as shown above. You need not have a separate hibernate configuration file (hibernate.cfg.xml ) to do this. I am using Hibernate annotations in this example, so I am listing all the annotated classes using the annotatedClasses property. All the Hibernate-related configurations can be done using the hibernateProperties.
We use a separate DAO class to interact with the database. Using a setter injection, we inject the Hibernate SessionFactory.
We have a MultiActionController class to handle the web requests, so we use a wildcard character in the bean name ("/user/*.htm").
Here is the User class with the Hibernate annotations. If you want to add any database-related constraints, then you need to do it here.
Our DAO class implements the UserDAO interface, and here, we have just two methods: one to save the user details and the other to list all the users.
In the DAO class, we use Hibernate Template to access the database. To create a Hibernate Template instance, you need a Session Factory. For this purpose, we injected the sessionFactory property in the Spring bean configuration file.
Hibernate Template is thread-safe and reusable. You need not manually open and close Session; Hibernate Template will do that for you.
The UserController class extends MultiActionController class. The UserDAOImpl instance is injected using a setter injection. In the add method, we call the saveUser() method and redirect the control to the "list.htm" url. This will invoke the list() method. In the list method, you add two things to the modelMap: the user list to display the list of users and an instance of the user object to bind the form fields in the userForm.jsppage.
In the jsp page, we use Spring Form tags to display the form fields and jstl tags to display the list of users.
Now you can execute the example by running the redirect.jsp page. You will see the following page.
After entering a few records, you will see the user's list displayed below.
0 Comments