Bruno Raljić

A Java Developer's Blog

Configure Spring with Hibernate – Basics – Part 1

Usually, when I write about something, I like to have a short briefing about the topic. But, that’s not the case this time. I don’t think some of you came here after typing “What is Spring/Hibernate” into google. Instead, I think you already have the idea what both Spring and Hibernate are and you just searched “How to configure Spring with Hibernate”. This is just another blog post about that, but I would like to go step-by-step tutorials for the begginers. Right now, here in codecentric Doboj, we have a two-weeks workshops running and I wanted to prepare some guidelines, so I can show them to our (future) candidates.

This tutorial is also different because it has EDWS (Exception Driven Write Style – I’ve just made up the term, but you’ll see what it is).

Configure Spring first

Ok, let’s start with a simple Maven project. Nothing special here. Now, lets invite Spring into the story. Add a Spring dependency to your pom.xml file.

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
	</dependencies>

Of course, add this above

	<properties>
		<org.springframework.version>3.2.1.RELEASE</org.springframework.version>
	</properties>

So, this is a starting point. Let’s suppose it’s enough and start googling something like “How to include Spring in web project”. After taking look at few tutorials, you’ll see that the web.xml needs to be configured for Spring. You can google also for a web.xml example (and also for the proper location). After finding out that you need an extra folder called WEB-INF, your project will look like this:

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.Spring documentation

Ok then, let’s add context-param and listener, as they suggested in the Spring documentation.

Add the following to your web.xml file

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

If you don’t specify the contextConfigLocation context parameter, the ContextLoaderListener will look for a /WEB-INF/applicationContext.xmlSpring documentation

So, it means you can also use a different name, but let’s stick to this one for now. Notice the asterix symbol, it will get all the files that starts with applicationContext and ends with .xml.

You can find on the internet sample of the applicationContext.xml. Let’s add it to our project, of course also to the WEB-INF folder.

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http: //www. springframework.org/schema/beans/spring-beans-3.0.xsd
	http: //www. springframework.org/schema/security
	http: //www. springframework.org/schema/security/spring-security-3.0.xsd">
	
</beans:beans>

*Note: As you can see, I’ve added spaces in the schema locations, because of link formatting (don’t ask why, it has something to do with code formatting, thanks). Remove them when you copy it.

When we try to start our server (I used Tomcat 7 for this tutorial), we’ll see something like this:

java.lang.ClassNotFoundException: 
    org.springframework.web.context.ContextLoaderListener

Does it ring any bells? Maven dependencies. As you can see from the package, we need spring-web

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

After adding it, we don’t have any exceptions and for now we can consider this basic Spring configuration as completed (until we find out some new exceptions).

Configure Hibernate now

Next step is to google “configure spring 3 with hibernate…” and as we type, we will see hibernate 4 as suggestion. Ok, let’s put some new dependencies into our pom.xml file. For now, only hibernate-core.

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.1.10.Final</version>
		</dependency>

After some searches, you’ll probably end up on the Spring’s blog where you can find a suggestion to add a following stuff to your applicationContext.xml

	<beans:bean id="sessionFactory" 
             class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"></beans:bean>
	<beans:bean id="transactionManager" 
             class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory" ref="sessionFactory"/>
	</beans:bean>

Expand your pom.xml file, as you can see there is new spring package called orm.

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

As you may know, Hibernate is a JPA implementation. After some searches on the net, you’ll find out something that is called entityManager. Let’s try to include it.

	<beans:bean id="entityManagerFactory" 
            class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<beans:property name="persistenceXmlLocation" value="classpath:persistence.xml" />
		<beans:property name="persistenceUnitName" value="blogTutorialPU" />
		<beans:property name="dataSource" ref="dataSource"/>
	</beans:bean>
	<beans:bean id="transactionManager" 
            class="org.springframework.orm.jpa.JpaTransactionManager">
		<beans:property name="entityManagerFactory" ref="entityManagerFactory"/>
	</beans:bean>
	<tx:annotation-driven transaction-manager="transactionManager" />

You’ll eventually get an error on this because we don’t have tx: defined as a namespace. Find it on the net and add it. Also update the schemaLocation


http://www.springframework.org/schema/tx


http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

You also need spring-tx, spring-jdbc and spring-beans dependency (all of this you can see from the specific exceptions when deploying your application).

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

Now, another exception, that will try to say you didn’t define dataSource. Add the following to your applicationContext.xml

	<beans:bean id="dataSource" 
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<beans:property name="url" 
                    value="jdbc:mysql://127.0.01/your_database_name?characterEncoding=UTF-8" />
		<beans:property name="username" value="username_goes_here" />
		<beans:property name="password" value="password_goes_here" />
	</beans:bean>

Next exception is telling us we need a JDBC driver so we will add it.

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>

Now we have something like this

java.io.FileNotFoundException: 
class path resource [persistence.xml] cannot be opened because it does not exist

which is correct, we actually don’t have it. So, let’s create one. If you don’t know where to put it, type this in the google: “default location for persistence.xml”.

In all cases, persistence.xml always resides in {root-of-persistence-unit}/META-INF/ directory. Java How To

after that, google for the minimal persistence.xml file. You’ll find something similar to this:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 

http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

             version="2.0">
   <persistence-unit name="blogTutorialPU">
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
      </properties>
   </persistence-unit>
</persistence>

As a result of all of this, you’ll get the following message: “No PersistenceProvider specified in EntityManagerFactory configuration, and chosen PersistenceUnitInfo does not specify a provider class name either”. After searching on google, you can realize you are missing a provider tag, so let’s add this line right after the opening persistance-unit tag

<persistence-unit name="blogTutorialPU">
      <provider>org.hibernate.ejb.HibernatePersistence</provider> 
      <!-- The rest -->
   </persistence-unit>
</persistence> 

Next one: Cannot find class [org.hibernate.ejb.HibernatePersistence]. If you can remember the link (Spring blog) I gave you at some point here, you’ll see they suggested you to include this

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.1.10.Final</version>
		</dependency>

At this point, you may have some exceptions related to the database connections, try to configure DB parameters. And that’s all. At least I didn’t get any exceptions.

Conclusion

This is, for sure, a different kind of tutorial. I’ve started from scratch and tried to “simulate” process of integrating new technologies when you do it for the first time. I must admit, this is not an easy job, especially if you are doing it for the first time. There are lot of tutorials telling only part of the story. Good tutorial is hard to find in all this mess we’re calling internet. With this blog I’m also contributing to that mess, but, maybe it can be useful to someone.

Keep in mind, this is the very basic configuration. I’ll continue to write about this topic, create some model classes, DAO, services etc. It will be based on this configuration.

Also, if you have something to add, if you’ve noticed something wrong here, feel free to post a comment, I will appreciate it.

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Show my latest blog post with this comment!