Spring 3 has finally been released, a while back, with it’s all new features offering a better developer experience. But there hasn’t been any straight forward tutorial that could set you up on your path to roll out your application using dependency injection and web layer from Spring 3 and domain repositories through good old Hibernate. At least I couldn’t find such a helpful stuff which i could use as a stub for my next project rapidly.
There’s already a tool(actually a great code-generator “Spring Roo”) which brings up a Spring 3 based project within minutes but that doesn’t tell you how features from Spring 3 actually work. To learn that, let’s build our own project step by step.
This tutorial will be broken into three parts. By the end of this series it’ll have all the good stuff from Spring (that is Dependency Injection, MVC, Repository, Transaction demarcations, Aspects and all the fun) the Spring 3 way. We’ll be using Hibernate for relational persistence mapping.
In this Part(that is Part A) we will create a maven project first and make it talk to our database through Hibernate. So let’s start some coding by creating a maven project.
mvn archetype:create -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.springhibernate.integration -DartifactId=spring-hibernate-webapp
Let’s get into our newly created “spring-hibernate-webapp” directory and make this baby work with Intellij Idea by executing
mvn idea:idea
Of course you can use any IDE of your choice. Anyways, after you see a “BUILD SUCCESSFUL” message on the command line, open this project into Intellij Idea. To make this project use Spring 3, Hibernate, Log4j, some Apache libraries and a couple of maven plugins etcetera we need to configure our pom.xml (since pom.xml is fairly long, i’ve avoided writing it’s content here. You can look at the source directly at google-code hosting of this project).
Let’s configure Hibernate for this project and march towards the end of this part of series.
- Under ‘src/main’ you should have a source folder named ‘java’ (if not then create it).
- Under that folder create a package ‘com.springhibernate.integration’.
- Create a class HibernateUtils.java under that package.
- At this point, to verify that all your maven dependencies are resolved and that your project setup is clean, you can create a main method inside inside HibernateUtils.java to print a greeting message like this.
package com.springhibernate.integration; import com.springhibernate.integration.model.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;</code> /** * @author Nabeel Ali Memon */ public class HibernateUtils { public static void main(String[] args) { System.out.println("Working Correctly upto this point"); } } - To execute it, go to command line and run these maven commands:
mvn compile mvn -e exec:java -Dexec.mainClass="com.springhibernate.integration.HibernateUtils"
And you should successfully see “Working Correctly upto this point”.
- Now we need a relational database and a table to persist/retrieve our data. For all practical purposes, let’s use MySQL by creating a database, a table and one entry to that table as following.
create database test; use test; create table user ( user_id int(11) primary key, first_name varchar(30), last_name varchar(30), email varchar(30) ); insert into user values (1, 'Nabeel', 'Memon', 'nabeelalimemon@gmail.com');
- We’r done with the database part. Let’s come back to our IDE and under the folder ‘src/resources’ create a new folder named ‘mappings’ and create a mapping file named ‘user.hbm.xml’ inside that folder. This mapping file should look like this:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.springhibernate.integration.model.User" table="USER"> <id name="id" column="USER_ID"> <generator class="increment"/> </id> <property name="firstName" column="FIRST_NAME"/> <property name="lastName" column="LAST_NAME"/> <property name="email" column="EMAIL"/> </class> </hibernate-mapping> - Under the package ‘src/main/java/com/springhibernate/integration’ create a package named ‘model’ and under that package create a class ‘User.java’ which is simply a Hibernate POJO for User entity.
package com.springhibernate.integration.model; /** * @author Nabeel Ali Memon */ public class User { private Long id; private String firstName; private String lastName; private String email; public User() { } 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 String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } - Hey we haven’t provided the hibernate configuration file yet, so let’s create one under ‘/src/resources’ named ‘hibernate.cfg.xml’
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">username</property> <property name="connection.password">password</property> <property name="hibernate.format_sql">true</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="hibernate.show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!--property name="hbm2ddl.auto">update</property--> <mapping resource="mappings/user.hbm.xml"/> </session-factory> </hibernate-configuration> - So now let’s modify our ‘HibernateUtil.java’ exposing Hibernate Session Factory provider method(static) and get it to do some real stuff
package com.springhibernate.integration; import com.springhibernate.integration.model.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * @author Nabeel Ali Memon */ public class HibernateUtils { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void main(String[] args) { Session session = getSessionFactory().getCurrentSession(); session.getTransaction().begin(); User user = (User) session.get(User.class, new Long(1)); System.out.println("user's email id is: "+user.getEmail()); session.getTransaction().commit(); } }
Simply execute the HibernateUtil.java file from (your IDE or) command line using maven exec plugin like we did before and you should see our user’s email address printed to screen.
That marks our project’s Hibernate usability. Hang on for the next part in which we actually configure Spring 3 in this project and introduce a Repository layer, Transactions and Logging Aspect being handled by Spring.
Update 1: Spring 3 integrated with Hibernate Part-B of this tutorial series is available now.
Update 2: I’ve hosted the entire project at code.google.com and have open sourced it under Apache 2 license. Enjoy!
1. Pingback by Spring 3 integrated with Hibernate Part-B | Stuff about Java and technology
9/Jul/2010 at 10:29 am
[...] Stuff about Java and technology Just another WordPress site Skip to content HomeAbout ← Spring 3 integrated with Hibernate Part-A [...]
2. Pingback by Spring 3 integrated with Hibernate Part-B « Stuff about Java and technology
15/Jul/2010 at 9:48 pm
[...] must have reached this page after covering the first part of this tutorial series Spring 3 integrated with Hibernate part A. If not, then you need to go through that part prior to reading [...]
3. Comment by custom chrome rims
11/Sep/2010 at 4:50 pm
im feeling it
4. Comment by physical therapist
24/Sep/2010 at 3:13 am
found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later
5. Comment by ssssdsdfg
25/Sep/2010 at 10:52 am
first post
6. Comment by Feedback Form
5/Oct/2010 at 8:25 pm
last few days our class held a similar talk about this subject and you show something we have not covered yet, thanks.
- Laura
7. Comment by willy
6/Oct/2010 at 2:41 pm
when i open the intellij .just give me a hints:older format.what can i do??emergency
8. Comment by Nabeel Ali Memon
6/Oct/2010 at 3:52 pm
If Intellij pops up a dialog box about older version then let it convert to the newer version. Else just get the source and do “create a new project from existing source” in intellij.
9. Comment by willy
7/Oct/2010 at 6:57 am
thank you~
10. Comment by aparadekto
28/Oct/2010 at 6:48 am
Hey, I can’t view your site properly within Opera, I actually hope you look into fixing this.
11. Comment by veterinary assistant
13/Nov/2010 at 9:02 am
Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!
12. Comment by Jena Bjornstad
17/Nov/2010 at 1:14 am
The well written summary encouraged me a lot! Saved your site, extremely excellent categories everywhere that I read here! I appreciate the information, thanks.
13. Comment by Ron Tedwater
18/Nov/2010 at 6:36 am
Great work keep it coming
14. Comment by Pa Corid
18/Nov/2010 at 6:45 am
It is your turn to come up with that concept that clarifies dilemmas with so well.
15. Comment by paul
23/Nov/2010 at 1:23 pm
great post. Anyways, i wanna share also a spoon-feed tutorial on Spring MVC
http://www.adobocode.com/spring/a-spring-web-mvc-tutorial
and add step-by-step Hibernate JPA capabilities tutorial to it:
http://www.adobocode.com/spring/adding-crud-capability-to-spring-mvc
hope it will help people!
16. Comment by bet365
25/Nov/2010 at 6:56 pm
how are you!This was a really superb Topics!
I come from roma, I was luck to come cross your Topics in digg
Also I learn much in your Topics really thanks very much i will come every day
17. Comment by maria andros
29/Nov/2010 at 11:11 am
Hey there this is a fantastic post. I’m going to e-mail this to my pals. I came on this while exploring on aol I’ll be sure to come back. thanks for sharing.
18. Comment by robert
28/Jul/2011 at 1:34 pm
hey dude …wake up now its time to use hibernate with spring..
its much easier to play with db with daos…duffer
19. Comment by chmo
9/Aug/2011 at 6:30 pm
you suggest compiling HibernateUtils.java before creating User.java, though importing the latter.
20. Comment by chmo
10/Aug/2011 at 1:54 pm
Please, correct # 7. Not “src/resources” but “src/main/resources”
21. Comment by invar
24/Aug/2011 at 1:32 pm
Can you either post the full pom.xml here, or make it available again in Google Code? Your Git repository there seems to be empty. Thanks!
22. Comment by intel3
6/Dec/2011 at 6:08 am
Btw your tutorial is excellent. Just one question, how do i build the project using eclipse…does the version matter? Thanks!
23. Comment by Michael
7/Dec/2011 at 9:18 pm
I am not sure why people think this post is great? The code does not use Spring Annotations nor Hibernate annotations. So it should not be called “Spring 3 integrated” There is nothing from Spring 3 whatsoever.
24. Comment by navi
30/Jan/2012 at 11:38 am
please give me simple application that show the spring 3.0 and hibernate work flow.actually am new in spring,but i have urgent project work.
25. Comment by jameel
2/Mar/2012 at 1:44 pm
Hi, the link to you pom.xml is not working. could you please make it available again in Google Code?
Thank ou
26. Comment by Tommy
21/Mar/2012 at 1:56 am
This is the problemt with 98% of the spring/hibernate documentation around the interwebz. It’s all outdated!