sprig3MVC+Hibernate整合

这篇文章简要介绍了如何使用spring3MVC注解和hibernate完成项目

用Eclipse作为开发工具,下图为项目结构

项目结构:

project-structure

需要的jar包:

lib1

lib2

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<
web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

<url-pattern>*.html</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

</web-app>

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(20NOT NULL auto_increment,
`article_name` varchar(20NOT 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();
  }
}

 ArticleService.java

This is the interface which declares methods which will be used in controller class.

package net.roseindia.service;

import java.util.List;

import net.roseindia.model.Article;

public interface ArticleService {

  public void addArticle(Article article);

  public List<Article> listArticles();
}

ArticleServiceImpl.java

This is the implementation class of ArticleService Interface. It defines all the methods declared in ArticleService interface. These methods uses Dao classes to interact with the database.

@Service("articleService") annotation is used to declare it as service bean and its name articleService will be used to auto wire its instance in controller class.

@Transactional annotation is used to declare the method transactional. You can also use this at the class level to declare all methods transactional.

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 void addArticle(Article article) {
    articleDao.saveArticle(article);
  }

  public List<Article> listArticles() {
    return articleDao.listArticles();
  }

}

ArticleController.java

This is the spring controller class which handles the request, processes it and returns back to the client.

@Controller annotation declares this as a controller class.

@RequestMapping("/articles") annotation tells Spring to process all requests beginning with /articles.

@RequestMapping(method = RequestMethod.GET) annotation tells Spring to process the request url /articles.html.

package net.roseindia.controller;

import java.util.HashMap;
import java.util.Map;

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.validation.BindingResult;
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(value = "/save", method = RequestMethod.POST)
  public ModelAndView saveArticle(@ModelAttribute(" article"Article  article,
      BindingResult result) {
     articleService.addArticlearticle);
    return new ModelAndView("redirect:/articles.html");
  }

  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView listArticles() {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("articles",  articleService.listArticles());

    return new ModelAndView("articlesList", model);
  }

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  public ModelAndView addArticle(@ModelAttribute("article"Article article,
      BindingResult result) {
    return new ModelAndView("addArticle");
  }

}

 articlesList.jsp

This jsp file is called when /articles.html is requested.

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

<html>

<head>

<title>All Articles</title>

</head>

<body>

<h1>List Articles</h1>

<a href="articles/add.html">Add Article</a>

<c:if test="${!empty articles}">

<table>

<tr>

<th>Article ID</th>

<th>Article Name</th>

<th>Article Desc</th>

<th>Added Date</th>

</tr>

<c:forEach items="${articles}" var="article">

<tr>

<td><c:out value="${article.articleId}"/></td>

<td><c:out value="${article.articleName}"/></td>

<td><c:out value="${article.articleDesc}"/></td>

<td><c:out value="${article.addedDate}"/></td>

</tr>

</c:forEach>

</table>

</c:if>

</body>

</html>


addArticle.jsp
This jsp file is called when  articles/add.html  is requested.

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

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head><title>Add Article</title></head>

<body>

<h1>Add Article</h1>

<c:url var="viewArticlesUrl" value="/articles.html" />

<a href="${viewArticlesUrl}">Show All Articles</a>

<br />

<br />

<c:url var="saveArticleUrl" value="/articles/save.html" />

<form:form modelAttribute="article" method="POST" action="${saveArticleUrl}">

<form:label path="articleName">Article Name:</form:label>

<form:input path="articleName" />

<br />

<form:label path="articleDesc">Article Desc:</form:label>

<form:textarea path="articleDesc" />

<br />

<input type="submit" value="Save Article" />

</form:form>

</body>

</html>


index.jsp
This is the index page which is called by default for application.

<%@ 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>Spring 3 MVC and Hibernate 3 Example application using Annotations</title>

</head>

<body>

<h1>Spring 3 MVC and Hibernate 3 Example application using Annotations</h1>

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

<a href="articles/add.html">Add Article</a>

</body>

</html>

When we compile the application and run, it displays the output as below:

index

Click on List of Articles link. It displays all articles as below:

list

Click on Add Article link, it let you add article in database.

add



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值