Spring 3 MVC and hibernate 3 example Part 2

Source: Internet
Author: User
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 shoshould 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. annotationsessionfactorybeanTo 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.

@ EntityAnnotation is used to declare the pojo as persistent entity.

@ TableAnnotation is used to map the pojo class to the table. In our case it is'Article'Table in database.

@ IDRepresents the identifier property.

@ GeneratedvalueDeclares that the Identifier value will be generated by the database automatically.

@ ColumnIs 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 classArticledaoInterface.

@ Repository ("articledao ")Declares that the annotated class is a "Dao ".

@ AutowiredIs 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();
  }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.