This tutorial explains how to use annotations with spring 3 MVC and hibernate 3 based application to make the development easier and faster than ever before.

dispatcher-servlet.xml:

<context:property-placeholder> element specifies the location where to find the properties file. In our case it is jdbc.properties which should be available in class path. So we put this file within source folder in eclipse so that it can be put into the classes folder when deployed into the server.

<context:component-scan> element specifies from where to look for annotated components like @Repository, @Autowired etc.

<tx:annotation-driven> element specifies spring to look for @Transactional beans.

<bean id="dataSource"> provides properties to hibernate to make it able to create session factory.

Hibernate uses instance of session bean of typeorg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean to make  domain objects be able to get annotated at the code level rather than defining in xml files.

<property name="annotatedClasses"> element provides hibernate the list of annotated classes. 


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

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

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

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

http://www.springframework.org/schema/context/spring-context-3.0.xsd

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


http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:property-placeholder location="classpath:jdbc.properties" />

<context:component-scan base-package="net.roseindia" />

<tx:annotation-driven transaction-manager="hibernateTransactionManager"

/>

<bean id="jspViewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/WEB-INF/view/" />

<property name="suffix" value=".jsp" />

</bean>

<bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="${database.driver}" />

<property name="url" value="${database.url}" />

<property name="username" value="${database.user}" />

<property name="password" value="${database.password}" />

</bean>

<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

<property name="dataSource" ref="dataSource" />

<property name="annotatedClasses">

<list>

<value>net.roseindia.model.Article</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">${hibernate.dialect}</prop>

<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>

</props>

</property>

</bean>

<bean id="hibernatetransactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />

</bean>

</beans>


jdbc.properties

This file contains set of key and value pairs. The key is used in places to refer the value.


database.driver=com.mysql.jdbc.Driver

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

database.user=root

database.password=root

hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

hibernate.show_sql=true


Create Database and Table:

We are using the database and table given below in our application. Use the following sql script and create table. 

​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`)
)​

 Article.java

Article is POJO class which hibernate uses to insert or retrieve data from database.

@Entity annotation is used to declare the POJO as persistent entity.

@Table annotation is used to map the POJO class to the table. In our case it is 'article' table in database.

@Id represents the identifier property.

@GeneratedValue declares that the identifier value will be generated by the database automatically. 

@Column is used to map the property to the column of the table. 

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;
  }  
}​

ArticleDao.java

This is an interface declaring the methods needed for the application. 

package net.roseindia.dao;

import java.util.Date;
import java.util.List;

import net.roseindia.model.Article;


public interface ArticleDao {
  // To Save the article detail
  public void saveArticle ( Article Article );
  
  // To get list of all articles
  public List<Article> listArticles();
}​

ArticleDaoImpl.java

This is the implementation class of  ArticleDao interface.

@Repository("articleDao") declares that the annotated class is a "DAO".

@Autowired is being used to make the SessionFactory instance available automatically by spring.

Now, define the methods declared in ArticleDao interface using hibernate.

package net.roseindia.dao;

import java.util.Date;
import java.util.List;

import net.roseindia.model.Article;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {

  @Autowired
  private SessionFactory sessionFactory;

  // To Save the article detail
  public void saveArticle(Article article) {
    article.setAddedDate(new Date());
    sessionFactory.getCurrentSession().saveOrUpdate(article);
  }
  
  // To get list of all articles
  @SuppressWarnings("unchecked")
  public List<Article> listArticles() {    
    return (List<Article>) sessionFactory.getCurrentSession().createCriteria(Article.class).list();
  }
}​