Bruno Raljić

A Java Developer's Blog

Configure Spring with Hibernate – Basics – Part 2

Ok, I will continue with the Spring-Hibernate configuration I’ve started in my previous post.

Part 2 will also continue in the Exception Driven Write Style manner. It also means that I’m configuring my project as I’m writting this post.

Short description

In short words, I’ll create one model class, service, DAO, few servlets and make it all work together (I hope so). We will create something like a blog platform where we will have one page with the all blog posts, one for the single blog post and one with the functionality to add new post. Nothing special, but I think it’s enough for this purpose

Model class

Let’s create a model class BlogPost. Right now, I’m thinking of few fields that we can use here such as title, blog post body, date when it’s created and date when it was updated. I put it in the com.brunoraljic.blog.model package.

	private String title;

	private String content;

	private Date dateCreated;

	private Date dateUpdated;

Services and DAO

Create two interfaces and two implementations. BlogPostService is an interface with a concrete implementation in the BlogPostServiceImpl. It’s same for Dao. We will have BlogPostDao and BlogPostDaoImpl. So, right now you should have something like this:
project3

Now, we will create one method getAllBlogPosts() in our DAO. Remember, declare it in interface and implement it in the actual implementation. We will also create this method in a same way, but in our service. There won’t be any logic in it, so we will just call DAO’s method. In order to do that, our Service need to have DAO as a field. We will have something like this:

public class BlogPostServiceImpl implements BlogPostService {

	private BlogPostDao blogPostDao;

	/**
	 * @see com.brunoraljic.blog.service.BlogPostService#getAllBlogPosts()
	 */
	public List<BlogPost> getAllBlogPosts() {
		return blogPostDao.getAllBlogPosts();
	}

}

Spring configuration

We have configured Spring, and the next step is to configure this Service and DAO using it. In this tutorial, I’ll set it up in the applicationContext.xml, although there is also another way to do it. Add the following to your applicationContext.xml

	<!-- Services -->

	<beans:bean id="blogPostService"
		class="com.brunoraljic.blog.service.impl.BlogPostServiceImpl">
		<beans:property name="blogPostDao" ref="blogPostDao" />
	</beans:bean>

	<!-- DAO -->

	<beans:bean id="blogPostDao"
		class="com.brunoraljic.blog.dao.impl.BlogPostDaoImpl" />

Now, when we have this, let’s try to deploy our application. Soon after deploy, I’ve realised I’m missing the setter for the DAO. Add a setter also in your Service. You can see it from the exception message: Bean property 'blogPostDao' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

Our DAO needs an entity manager, so we will add it in the xml file (we will add already defined entityManagerFactory, but using this factory we can get an entity manager). Replace the last two lines you’ve added with this

	<beans:bean id="blogPostDao"
		class="com.brunoraljic.blog.dao.impl.BlogPostDaoImpl">
		<beans:property name="emf" ref="entityManagerFactory" />
	</beans:bean>

and in the BlogPostDaoImpl add this

public class BlogPostDaoImpl implements BlogPostDao {

	private EntityManagerFactory emf;

	public List<BlogPost> getAllBlogPosts() {
		// TODO Auto-generated method stub
		return null;
	}

	public void setEmf(EntityManagerFactory emf) {
		this.emf = emf;
	}

}

After I’ve deployed my application, I got no exceptions so I think we can continue. Now, let’s expand our method for getting all blog posts.

	@SuppressWarnings("unchecked")
	public List<BlogPost> getAllBlogPosts() {
		EntityManager em = emf.createEntityManager();
		return (List<BlogPost>) em.createQuery("from BlogPost").getResultList();;
	}

Right now implementation will be like this, in the next blog I could tidy up the details, perhaps create more abstract DAO or something like that. But for now, I think this will do the work. Let’s restart the server and see if there are some exceptions. I’ve got no exceptions, so I’ll move forward.

Database

One of the things we need to set up is the database, and the tables that will represent our entities, BlogPost in our case. Let’s create a script and put it the folder DEV (which we will also create). This folder can be on the root of the project. I’ve wrote a simple create table script. In a real world, you would add few more things to this script, but for this purpose I think it will be enough.

CREATE TABLE blogposts (
  blogpost_id INT NOT NULL AUTO_INCREMENT ,
  title VARCHAR(100) NOT NULL ,
  content TEXT NOT NULL ,
  date_created TIMESTAMP NOT NULL ,
  date_updated TIMESTAMP NULL ,
  PRIMARY KEY (blogpost_id) ,
  UNIQUE INDEX blogpost_id_UNIQUE (blogpost_id ASC) 
);

Annotations

JPA annotations enable you to define how the JPA provider persists your Java class. Force.com

Here are some basic JPA annotations for our entity. We will add them to our BlogPost so it will look something like this (note that I’m using JPA annotations, not Hibernate:

@Entity
@Table(name = "blogposts", schema = "tutorial")
public class BlogPost {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int blogpostId;

	@Column(name = "title")
	private String title;

	@Column(name = "content")
	private String content;

	@Column(name = "date_created")
	private Date dateCreated;

	@Column(name = "date_updated")
	private Date dateUpdated;

    // Getters and setters
}

Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase, and PostgreSQL. Oracle does not support IDENTITY columns but its is possible to simulate them using sequence objects and triggers.Identity and sequencing on wikibooks.org

As you see, I’ve added one extra field, because every entity needs to have @Id.

Let’s say this is enough for us to continue, although my experience is telling me that we need to do something with the content field, but, let’s deal with that when time comes.

Servlet

This is the simple application so I’ll just add few servlets for every action. Let’s start with the list of all blog posts (something like index page for our blog). We will also define and map this servlet in our web.xml file. Perhaps, you can read a few things about servlet also.

I’ll create a new package com.brunoraljic.blog.servlet for the servlets. Soon after adding a Servlet, you’ll realize that you’re missing some dependencies. Add this to your pom.xml

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>

Scope provided will exclude the servlet-api.jar from your war file. After this, let’s create a simple implementation which will get all our blogposts. For the beginning, I’ll implement only the first part which will get the blogposts to see if I set everything right with Hibernate. Later, I’ll create a jsp index page where the results will be shown.

Insert a test data in your database (you can create a script also, put it in the DEV folder), so we have something to work with until we implement the functionality to add a new blog post.

Data flow

Just a few words about the data flow. We will make a request on a specific servlet. In our case we want to get all the blog posts. Our servlet will use BlogPostService‘s method to get them all. If you remember, we defined our service to have BlogPostDao. So, the service will just call the DAO method for getting the posts. DAO object will serve just for that. Accessing data and providing what is been asked for. Nothing else. No additional logic in your DAO should be present! If you have some logic, do it in your Service. When you get what you want, pass it back to the Servlet and eventually put it in the request’s attribute.

Implementing doGet() method

As I said, we need our BlogPostService, so we will first get it via WebApplicationContext. You can find this if you google “how to get spring bean in servlet”.

		WebApplicationContext springContext = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		BlogPostService blogPostService = springContext.getBean(
				"blogPostService", BlogPostService.class);

		List<BlogPost> blogposts = blogPostService.getAllBlogPosts();

Also, add this to your web.xml

	<servlet>
		<display-name>AllBlogpostsServlet</display-name>
		<servlet-name>AllBlogpostsServlet</servlet-name>
		<servlet-class>com.brunoraljic.blog.servlet.AllBlogpostsServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>AllBlogpostsServlet</servlet-name>
		<url-pattern>/index</url-pattern>
	</servlet-mapping>

Now, let’s try it and see what we will get (some exceptions are expected, of course). After trying to access /index, I got NullPointerException in the DAO. Google told me I have something in the persistence.xml that I don’t need. Remove this (and, of course, do some searches why we don’t need this).

<jta-data-source>java:/DefaultDS</jta-data-source></code>

After removing that, I got the following exception

javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: 
Unknown column 'blogpost0_.blogpostId' in 'field list'

Which is OK, as we forgot to say which column it is, and it is searching by default for blogpostId column. Change a little bit your ID field so it looks like this

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "blogpost_id")
	private int blogpostId;

After this, I get no new exceptions, so I can move to the next step.

Display results on index.jsp

To see the actual results, we will add a simple JSP page, containing some JSTL (which means – more dependencies in your pom.xml file). Add this:

		<!-- JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

Let’s first continue our doGet() implementation. All we need is to put this list of blogpost somewehere and tell which page is the result of this servlet’s call.

		request.setAttribute("blogposts", blogposts);

		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher("/index.jsp");
		dispatcher.forward(request, response);

After this we need to create the index.jsp page. Within that page we will use a little bit of expression language to iterate through the list of blog post. You can google: How to include jstl in jsp and they will say you need to start your jsp page with something like this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach var="blogpost" items="${blogposts}">
	<h1>${blogpost.title}</h1>
	<p>${blogpost.content}</p>
	<p>Created: ${blogpost.dateCreated}</p>
	<c:if test="${not empty blogpost.dateUpdated}">
		<p>Updated: ${blogpost.dateUpdated}</p>
	</c:if>
	<hr />
</c:forEach>

As you may see, I didn’t apply any css, it was just to show you the results. I got something like this:

project4

And that’s all for now. I’ll continue to write about this topic, there are few more things I want to show you, and I can use this mini project. Now, my project looks like this:

project5

And, you can download my project, if you missed some points and compare it with your work. I hope it will help you.

, , , , , , , ,

One thought on “Configure Spring with Hibernate – Basics – Part 2

Leave a Reply

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

Show my latest blog post with this comment!