我是資深的電腦資訊從業員,曾於 Motorola 及 Philips 等跨國大型公司管理層工作十多年,具各類ERP資源管理系統及其它應用系統經驗,如QAD之MFG/PRO、SAP、Ufida(用友)、Kingdee(金蝶)、Microsoft's Dynamic、Wonderware's In-Track (SFC)、Webplan (SCM)、Hyperion (business intelligence)、Informatics (Data Warehouse)...等等。另外,我精於廠房車間之電腦資訊運作,擁有 CISSP 及 ITIL 認證,能提供日常資訊運作之檢測及審查,以提高操作效率。 本人誠意為各類大中小型廠房提供資訊審計、支援及意見,歡迎聯絡,電郵為




我想很多人會對"香港股票價位的歷史數據"有興趣,我已下載成Microsoft Access database version 2000 的文檔,資料由2008/1/1至2009/12/2,zip壓縮後也有11M,若索取請留你的PM我 。




Spring 4 and Hibernate 4 Integration Tutorial Part 1: XML Configuration

In enterprise Java application development, perhaps Spring and Hibernate integration is one of the most-demanded topic which most programmers are looking for and are facing with. Spring is the leading enterprise application framework, and Hibernate is the leading ORM framework so combination of these two guys would be a preferable choice in order to develop robust enterprise applications.
This is a step-by-step tutorial that helps you build a Spring-Hibernate application easily in a clear and concise way. In this first part, we demonstrate how to code a simple Spring MVC application that displays a list of users from MySQL database. The DAO implementation uses Hibernate’s SessionFactory to query against the database, instead of usingJdbcTemplate.
The following configuration approaches are used in the demo application:
  • Spring MVC: Annotations for controller and XML for bean definitions.
  • Hibernate: XML mapping for model class.
  • Web Application: using web.xml deployment descriptor file.
The following technologies and pieces of software are used throughout this tutorial:
  • Java 7
  • Spring framework 4.0.3.RELEASED
  • Hibernate ORM 4.3.5.Final
  • Spring Tool Suite IDE 3.5.1
  • Maven 3
  • Tomcat 7

1.    How Spring supports Hibernate Integration

Basically, in order to support Hibernate integration, Spring provides two key beans available in the org.springframework.orm.hibernate4 package:
  • LocalSessionFactoryBean : creates a Hibernate’s SessionFactory which is injected into Hibernate-based DAO classes.
  • HibernateTransactionManager : provides transaction support code for aSessionFactory . Programmers can use @Transactional annotation in DAO methods to avoid writing boiler-plate transaction code explicitly.
Let’s see how these concepts are implemented in a real project.

2.    Setting up Project

Let’s create a Spring MVC project using Spring Tool Suite IDE (See example:Spring MVC beginner tutorial with Spring Tool Suite IDE ), name it asSpringMvcHibernateXML .
Setting up Database
Execute the following MySQL script in order to create a database named usersdbwith a table named users :
create database usersdb;

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `password` varchar(45) NOT NULL,
  `email` varchar(45) NOT NULL,
  PRIMARY KEY (`user_id`)
Remember to insert some dummy data for testing purspose.
Project Structure
The following screenshot shows final structure of the project:
Spring MVC Hibernate project structure
NOTE: After completing this tutorial, you will create a project structure looks like the above.
Maven Dependencies
Declare versions for Java and Spring framework:
Update pom.xml file for the following dependencies:
  • Spring framework dependencies:
  • Hibernate ORM framework dependencies:
  • Java Servlet and JSP dependencies (for compilation only):
  • JSTL dependency:
  • Apache Commons DBCP dependency (for database connection pooling):
  • MySQL Connector Java dependency (JDBC driver for MySQL):
NOTE: You can see the whole content of pom.xml file in the attached project.

3.    Coding Model Class Configuring Hibernate Mapping

Writing Model Class
Create a new class named in the package net.codejava.spring.modelwith the following source code:
package net.codejava.spring.model;

public class User {
  private int id;
  private String username;
  private String password;
  private String email;

  // getters and setters are removed for brevity

This model class is used to map the table users and the database to a plain-old Java object (POJO).
Creating Hibernate XML Mapping for the Model Class
We need to create a Hibernate XML mapping file to map the User class to theusers table in database. Create a User.hbm.xml file under the same package as theUser class with the following XML code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="net.codejava.spring.model">
  <class name="User" table="USERS">
    <id name="id" column="USER_ID">
      <generator class="native"/>
    <property name="username" column="USERNAME" />
    <property name="password" column="PASSWORD" />
    <property name="email" column="EMAIL" />
NOTE: For more information about Hibernate XML mapping, see: Hibernate One-to-Many XML Mapping Example .
Creating Hibernate XML Configuration File
Create hibernate.cfg.xml file under the root of classpath (right in src directory in the project) with the following XML code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>  
    <mapping resource="net/codejava/spring/model/User.hbm.xml"/>
This Hibernate configuration file declares which resources need to be mapped (theUser.hbm.xml file in this case).

4.    Coding DAO Classes

Writing UserDAO interface
Create a very simple DAO interface for the User class as the class:
package net.codejava.spring.dao;

import java.util.List;

import net.codejava.spring.model.User;

public interface UserDAO {
  public List<User> list();
This interface declares only one method list() that retrieves all users from the database.
Writing UserDAO implementation
Here’s we code an implementation of the UserDAO interface, the UserDAOImplclass as follows:
package net.codejava.spring.dao;

import java.util.List;

import net.codejava.spring.model.User;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

public class UserDAOImpl implements UserDAO {
  private SessionFactory sessionFactory;

  public UserDAOImpl(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;

  public List<User> list() {
    List<User> listUser = (List<User>) sessionFactory.getCurrentSession()

    return listUser;

Notice in this class, a Hibernate’s SessionFactory object is injected via constructor by Spring. The list() method simply obtains the current session from theSessionFactory and queries for a list of all users in the database.
Pay attention to the @Transactional annotation provided by Spring - when a method is annotated by this annotation, Spring will inject transaction support code into the method - thus we don’t have two write any code to handle transaction explicitly.
Recommended Book: Spring in Action

5.    Configuring Spring Application Context

Now, we come to the most important part that wires Spring and Hibernate together through some XML configuration. Open the servlet-context.xml file undersrc/main/webapp/WEB-INF/spring/appServlet and update its content as follows.
Configuring Spring MVC View Resolvers
As usual, add the following declarations for Spring MVC annotation driven approach:
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="net.codejava.spring" />
The following declaration for a common view resolver that converts logical view names to actual JSP pages:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
Configuring DataSource Bean
We use Apache Commons DBCP for a data source with connection pooling capability:
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/usersdb"/>
  <property name="username" value="root"/>
  <property name="password" value="secret"/>
NOTE: Change database URL, username and password according to values in your environment. This data source will be injected to a SessionFactory bean below.
Configuring SessionFactory Bean
Spring 4 provides support for Hibernate 4’s SessionFactory through aLocalSessionFactoryBean which is actually a FactoryBean that creates a Hibernate’s SessionFactory which is then injected to Hibernate-based DAO beans. Here’s the bean declaration:
<bean id="sessionFactory"
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" value="classpath:hibernate.cfg.xml" />
Note that this LocalSessionFactoryBean requires a DataSource bean which is declared previously. The configLocation property specifies where Hibernate configuration file will be searched for. In this case, it is the hibernate.cfg.xml file in the classpath.
Configuring TransactionManager Bean
The following declaration is for automatic transaction support for theSessionFactory :
<tx:annotation-driven />
<bean id="transactionManager"
  <property name="sessionFactory" ref="sessionFactory" />
As mentioned in the UserDAOImpl class, we can specify transaction support by using the @Transactional annotation for transaction-aware methods.
Configuring DAO Bean
And finally, configuration for our UserDAOImpl bean - pretty simple:
<bean id="userDao" class="net.codejava.spring.dao.UserDAOImpl">
    <ref bean="sessionFactory" />
This bean will be then injected to a Spring MVC controller class which is described below.
NOTE: For the whole content of Spring application context configuration file, see the corresponding file in the attached project.
Recommended Book: Spring Integration in Action

6.    Coding Controller Classes

Write our Spring MVC controller class ( ) under thenet.codejava.spring package with the following code:
package net.codejava.spring;

import java.util.List;

import net.codejava.spring.dao.UserDAO;
import net.codejava.spring.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

 * Handles requests for the application home page.
public class HomeController {
  private UserDAO userDao;
  public ModelAndView home() {
    List<User> listUsers = userDao.list();
    ModelAndView model = new ModelAndView("home");
    model.addObject("userList", listUsers);
    return model;
Here, an implementation of the UserDAO is injected automatically by Spring (because @Autowired annotation is used). Remember the UserDAOImpl bean we declared in the Spring application context configuration file previously? It is injected to this controller automatically so that the handling method home() can use it to list all users from the database. And eventually, the home() method returns a view namedhome which is resolved an actual JSP page which is described below.

7.    Coding View Page

Create a home.jsp under the src/main/webapp/WEB-INF/views directory with the following content:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<%@ taglib uri="" prefix="c" %>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <div align="center">
    <h1>Contact List</h1>
    <table border="1">
        <c:forEach var="user" items="${userList}" varStatus="status">
        <td>${status.index + 1}</td>
This JSP page simply displays a list of users which is passed by the controller, by using JSTL tags.
Recommended Book: Spring in Practice

8.    Testing the Application

Deploy the SpringMvcHibernateXML application on Tomcat server and access its default page via the following URL:
If everything is going fine, you would see the following result:
Spring MVC Hibernate Example
Congratulations! You have completed our first part of Spring-Hibernate Integration series. You can download the attached project and experiment yourself. A deployable WAR file is also provided for your convenience.
Related Course: The Java Spring Tutorial