Hibernate 3 Query Example Part 1

Hibernate 3 well works with Spring framework. You can use Hibernate and Spring 3 for making the persistence layer for your web applications.

Hibernate 3 Query Example Part 1

Hibernate 3 Query Example Part 1

     

Hibernate 3 Query Example Part 1

Hibernate 3 well works with Spring framework. You can use Hibernate and Spring 3 for making the persistence layer for your web applications. Optionally Hibernate caching can also be used for caching the data and increase the database performance.

This example is developed using Hibernate 3 and Spring 3 MVC, and MySQL is used as backend of the application.

We have provided the sql for creating MySQL table and populate some data.

After completing this example you will be able to use Hibernate 3 in your Spring 3 based applications.

This tutorial  explains  how to create  Hibernate 3 query example with Spring 3  MVC based annotations. This example is created in ellipse IDE and run in tomcat server. In this example, we used the following jar files :

image

image

This tutorial applied following steps

Step 1 :

First we create Dynamic web project "Hibernate3QueryExample" in ecllipse IDE . Now we create index.jsp file under WebContent folder. The code of index.jsp are given as:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Hibernate 3 Query Example </title>

</head>

<body>

<h1>Hibernate 3 Query Example</h1>

<a href="articles.html">List of Articles</a>&nbsp;

<a href="articles/searcharticle.html">Search Article</a>

</body>

</html>

Step 2 :

Create database and table used in the example.

create database if not exists `db_roseindia`;

USE `db_roseindia`;

CREATE TABLE `article` (
`article_id` bigint(20) NOT NULL auto_increment,
`article_name` varchar(20) NOT NULL,
`article_desc` text NOT NULL,
`date_added` datetime default NULL,
PRIMARY KEY (`article_id`)
)

Step 3 :

Now create pojo class "Article.java"  under  " src/net/roseindia/model" directory . The code  of  "Article.java" given below :

package net.roseindia.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "article")
public class Article {

@Id
@GeneratedValue
@Column(name = "article_id")
private Long articleId;

@Column(name = "article_name", nullable = false, length=20)
private String articleName;

@Column(name = "article_desc", nullable = false)
private String articleDesc;

@Column(name = "date_added")
private Date addedDate;

public Article() { 
}
public Long getArticleId() {
return articleId;
}
public void setArticleId(Long articleId) {
this.articleId = articleId;
}
public String getArticleName() {
return articleName;
}
public void setArticleName(String articleName) {
this.articleName = articleName;
}
public String getArticleDesc() {
return articleDesc;
}
public void setArticleDesc(String articleDesc) {
this.articleDesc = articleDesc;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Date addedDate) {
this.addedDate = addedDate;
} 
}

Step 4:

Now create  controller class "ArticleController.java" under " src/net/roseindia/controller" directory. The code of "ArticleController.java" is given below :

package net.roseindia.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.roseindia.model.Article;
import net.roseindia.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/articles")
public class ArticleController {
	@Autowired
	private ArticleService articleService;
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView listArticles(HttpServletRequest request ) {
		Map model = new HashMap();
		if(request.getParameter("articleId")!=null && 
				(!(request.getParameter("articleId")).equals(""))){
			 Long articleId=Long.parseLong(request.getParameter("articleId"));
			 model.put("articles",  articleService.getArticleByArticleId(articleId));
		  }else{
			  model.put("articles",  articleService.listArticles());  
		  }
		return new ModelAndView("articlesList", model);
	}	
	@RequestMapping(value = "/searcharticle", method = RequestMethod.GET)
	public ModelAndView addArticle(@ModelAttribute("article") Article article) {
		return new ModelAndView("searcharticle");
	}	
	@RequestMapping(value = "/searcharticle", method = RequestMethod.POST)
	public ModelAndView saveArticle(@ModelAttribute(" article") Article  article) {		 
		
	    return new ModelAndView("redirect:/articles.html?articleId="+article.getArticleId());
	 }
}

Step 5:

Now create interface "ArticleDao.java" under "src/net/roseindia/dao" directory that declare some methods for the application. The code of "ArticleDao.java" given below :

package net.roseindia.dao;

import java.util.List;
import net.roseindia.model.Article;
public interface ArticleDao {
	// To get list of all articles
	public List
listArticles(); // get article list by articleId public List
getArticleByArticleId(Long articleId); }

Step 6:

Now  create  the class "ArticleDaoImpl.java"  under  "src/net/roseindia/dao" directory that implements "ArticleDao" interface .The code of  "ArticleDaoImpl.java" given below :

package net.roseindia.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import net.roseindia.model.Article;
@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {
	@Autowired	
	private SessionFactory sessionFactory;
	// To get list of all articles
	@SuppressWarnings("unchecked")
	public List
listArticles(){ return (List
) sessionFactory.getCurrentSession(). createCriteria(Article.class).list(); } public List
getArticleByArticleId(Long articleId){ return sessionFactory.getCurrentSession().createQuery("from Article " + "where articleId=:articleId") .setParameter("articleId", articleId) .list(); } }

Step 7:

Now create  interface "ArticleService.java" under "src/net/roseindia/service" directory that declare some method that use in controller . The code of  ArticleService interface given below :

package net.roseindia.service;

import java.util.List;
import net.roseindia.model.Article;
public interface ArticleService {
	public List
listArticles(); public List
getArticleByArticleId(Long articleId); }

Step 8:

Again create class "ArticleServiceImpl .java" under "src/net/roseindia/service" directory that implements interface ArticleService . The code of  "ArticleServiceImpl .java" given below :

package net.roseindia.service;

import java.util.List;
import net.roseindia.dao.ArticleDao;
import net.roseindia.model.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("articleService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ArticleServiceImpl implements ArticleService {
	@Autowired
	private ArticleDao articleDao;
	public ArticleServiceImpl() {
	}
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public List
listArticles() { return articleDao.listArticles(); } public List
getArticleByArticleId(Long articleId){ return articleDao.getArticleByArticleId(articleId); } }

Step 9 :

Again create  "jdbc.properties"  file under "src" folder that use for database related information. The  "jdbc.properties"  file describe as :

database.driver=com.mysql.jdbc.Driver

database.url=jdbc:mysql://localhost/db_roseindia

database.user=root

database.password=

hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

hibernate.show_sql=true