Spring 3 MVC and Hibernate 3 Example Part 2

9073 ワード

This tutorial explins how to use annotations with spring 3 MVC and hibernate 3 based appication to make the development easure and faster than ever before.
dispatcher-servlet.xml:
<context:property-placceholder> element specifes the location where to find the properties file.In our case it is jdbc.properties which shoud be available in class path.So we put this file within source folder in in eclipse the it caput
<context:component-scan> element specifes from where to look for annotated components like@Repository@Autowired etc.
<tx:annotationn-driven> element specifies spring to look for@Transation al beans.
<bean id=「dataSource」> provides properties to hibernate to make it able to create session factory.
ハイバーナuses instance of session bean of typeorg.spring frame ebook.orm.hibernate 3.annotations.AnnotationSession FactoryBen to make  domain object be able to get annotated at the code level rather than defining in xml files.
<property name=「annotated Class」> element provides hibernate the list of annotated clases. 
 id=「dataSource」class=「org.spring frame ebook.jdbc.datasource.DriverManagerDataSource」 name=「driverClass Name」 value=「$database.driver」 />  id=「session Factory」class=「org.springframe ebook.orm.hibernate 3.annotations.AnnotationSession FactoryBen」 name=「dataSource」 ref=「dataSource」 /> net.roserindia.model.Artcle name=「hibernate Properties」<props><prop> key=「hibernate.dialect」 key=「hibernate.show_sql」$ id=「hibernaetration Manager」class=「org.springframe ebook.orm.hibernate 3.Hibernettonict Manager」 name=「session Factory」 ref=「session Factory」 />
jdbc.properties
This file contains set of key and value pairs.The key is used in placces to refer the value.
database.driver=comp.mysql.jdbc.Driver database.url=jdbc:mysql://192.168.10.13/db_roeindia database.user=root databases.password=root hibernane.dialect=org.hibernate.dialect.MySQL 5 Dialect hiberrate.showsql=true
Create Database and Table:
We are using the database and table given below in our aplication.Use the follwing 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`)
)
 Artcle.java
Artcle is POJO class hibernate uses to insert or retrieve data from database.
@Entity annotation is used to declare the POJO as persistent entity.
@テーブル annotation is used to map the POJO class to the table.In our case it is'artic'table in database.
@Id represents the identifer property.
@GenerantedValue declares that the identifer value will be generated by the database atomaticaly. 
@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;
  }  
}
ArtcleDao.java
This is is an interface declaring the methods need for the appication.  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();
}
ArtcleDaoImpl.java
This is the implemention class of ArtcleDao インターフェース.
@Repository(「articaleDao」) declares that the annotated class a“DAO”.
@Autowired is being used to make the Session Factory instance available autically by spring.
Now,define the methods declead in ArtcleDao interface using hibernane.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();
  }
}