Spring mvc+Spring+hibernate整合

时间:2022-07-29 23:16:57

有段时间没有更新博客了,跟最近比较忙有关系。无聊搭建个Java web框架,反正好久没有自己搭建框架了,算是练练手了,今天我就来搭建一个框架,技术选型为Spring mvc+Spring+hibernate。若想搭建Spring mvc+Spring+Mybatis请看我上篇日志,好了废话不多说,见代码。

1、开发环境:jdk1.7,tomcat6,eclipse版本过高需要设置jdk

2、项目结构

Spring mvc+Spring+hibernate整合

2、Spring mvc+Spring+Hibernate框架搭建流程跟Spring mvc+Spring+Mybatis搭建类似

首先在web.xml中配置Spring监听器及加载文件,其次配置spring mvc的配置,并在web.xml中配置spring mvc的servlet,最后在配置Spring与Hibernate整合部分即sessionFactory、数据库连接池等

3、先看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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

<!-- 加载spring配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
            classpath:config/application-config.xml
        </param-value>
	</context-param>

<!-- spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
<!-- 配置编码 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<!-- spring mvc dispatcher -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/mvc-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
<!--错误页面配置 -->
	<error-page>
		<error-code>403</error-code>
		<location>/WEB-INF/view/error/403.jsp</location>
	</error-page>
	<error-page>
		<error-code>404</error-code>
		<location>/WEB-INF/view/error/404.jsp</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/WEB-INF/view/error/500.jsp</location>
	</error-page> 
</web-app>
4、 我们在来看看spring mvc的配置文件mvc-config.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd" default-autowire="byType">

<!-- 启动注解 -->
	<mvc:annotation-driven /> 
<!-- 扫描注解包 -->
	<context:component-scan base-package="com.demo"></context:component-scan>
<!-- 配置view页面 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".jsp" />
	</bean>
<!-- 加载application.properties文件,这个文件一般都配置了数据库及数据库连接池等 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
        <property name="location">  
        <value>classpath:config/application.properties</value>  
        </property>  
    </bean>  
	<!-- 静态文件 -->
	<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"></mvc:resources>
</beans>

 
5、 
常用配置信息如数据库连接池等信息,一般习惯配置在新的文件中application.properties 
#hibernate
hibernate.max_fetch_depth=3
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=10
hibernate.show_sql=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
jdbc.maxActive=50

c3p0.acquireIncrement=10
c3p0.minPoolSize=3
c3p0.maxPoolSize=200
c3p0.maxIdleTime=6000
6、 spring基本配置,及spring 事物数据库连接池等配置
基本配置application-config.xml

<?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:task="http://www.springframework.org/schema/task"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/task
		http://www.springframework.org/schema/task/spring-task.xsd
	    http://www.springframework.org/schema/cache
	    http://www.springframework.org/schema/cache/spring-cache.xsd">

	
	<!-- 扫描包 -->
 	<context:component-scan base-package="com.demo"/>
<!-- 注解配置 -->
    <context:annotation-config></context:annotation-config>
    <!-- 引人其他文件 -->
     <import resource="data-source-tx.xml"></import>
    
     <!-- hibernate ehcache 
    <cache:annotation-driven cache-manager="cacheManager"></cache:annotation-driven>
    
     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehcache"></property>
    </bean>
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
          p:configLocation="classpath:config/ehcache.xml" p:shared="true"/>-->

</beans>
hibernate的sessionFactory及数据库连接池配置datasource-tx.xml
<?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:jdbc="http://www.springframework.org/schema/jdbc" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc
		http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context.xsd">

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

	<!-- sessionFactory -->
	<bean id="sessionFactory" 
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.demo.model" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.current_session_context_class">thread</prop> 
            </props>
        </property>
    </bean>

	<!-- dataSource -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- these are C3P0 properties -->
		<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
		<property name="minPoolSize" value="${c3p0.minPoolSize}" />
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
		<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
	</bean>
	
	<!-- 配置Hibernate事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
   </bean>
   <!-- 事物注解配置 -->
   <tx:annotation-driven transaction-manager="transactionManager"/>    
       

</beans>

以上内容为配置内容,配置讲完了,下面以用户登录为测试案例

1、控制层controller

package com.demo.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.demo.model.User;
import com.demo.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/login",method=RequestMethod.GET,params="form")
	public String toLogin(Model model){
		User user = new User();
		model.addAttribute(user);
		return "user/login";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@Valid User user,BindingResult result){
		if(result.hasErrors()){
			return "user/login";
		}
		if(this.userService.login(user.getUsername(), user.getPassword())){
			return "user/success";
		}
		return "user/fail";
		
	}

}
2、实体层model

package com.demo.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1482055695347272535L;
	
	@Id
	@GeneratedValue
	private long id;
	
	private String username;
	
	private String password;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	

}

3、服务层service

服务层接口

package com.demo.service;

public interface UserService {
	
	public boolean login(String username,String password);

}
服务层实现类
package com.demo.service.impl;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo.dao.UserDao;
import com.demo.model.User;
import com.demo.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;

	@Override
	@Transactional
	public boolean login(String username, String password) {
		boolean flag = false;
		User user = this.userDao.findByUsernameAndPassword(username, password);
		if(user != null){
			if(username.equals(user.getUsername()) && password.equals(user.getPassword())){
				flag = true;
			}
		}
		return flag;
	}

}
4、持久层dao
package com.demo.dao;

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

import com.demo.model.User;
@Repository
public class UserDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		return this.sessionFactory.openSession();
	}
	
	public void close(Session session){
		if(session != null)
			session.close();
	}
		
	public User findByUsernameAndPassword(String username,String password){
    	String hsql="from User u where u.username= :username and u.password= :password";
        Session session = getSession();
        Query query = session.createQuery(hsql);
        query.setParameter("username", username).setParameter("password", password);
        User user = (User) query.uniqueResult();
        close(session);
        return user;
    }

}
5、sql脚本
/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50622
Source Host           : localhost:3306
Source Database       : demo

Target Server Type    : MYSQL
Target Server Version : 50622
File Encoding         : 65001

Date: 2016-07-19 20:36:51
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `kpi`
-- ----------------------------
DROP TABLE IF EXISTS `kpi`;
CREATE TABLE `kpi` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day` varchar(20) DEFAULT NULL,
  `state` varchar(20) DEFAULT NULL,
  `num` int(111) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of kpi
-- ----------------------------
INSERT INTO `kpi` VALUES ('1', '6月28日', 'success', '11');
INSERT INTO `kpi` VALUES ('2', '6月28日', 'fail', '22');
INSERT INTO `kpi` VALUES ('3', '6月29日', 'success', '33');
INSERT INTO `kpi` VALUES ('4', '6月29日', 'fail', '27');
INSERT INTO `kpi` VALUES ('5', '6月30日', 'success', '232');
INSERT INTO `kpi` VALUES ('6', '6月30日', 'fail', '123');
INSERT INTO `kpi` VALUES ('7', '7月1日', 'success', '235');
INSERT INTO `kpi` VALUES ('8', '7月1日', 'fail', '80');
INSERT INTO `kpi` VALUES ('9', '7月2日', 'success', '90');
INSERT INTO `kpi` VALUES ('10', '7月2日', 'fail', '324');
INSERT INTO `kpi` VALUES ('11', '7月3日', 'success', '325');
INSERT INTO `kpi` VALUES ('12', '7月3日', 'fail', '134');
INSERT INTO `kpi` VALUES ('13', '7月4日', 'success', '345');
INSERT INTO `kpi` VALUES ('14', '7月4日', 'fail', '245');
INSERT INTO `kpi` VALUES ('15', '7月5日', 'success', '124');
INSERT INTO `kpi` VALUES ('16', '7月5日', 'fail', '256');
INSERT INTO `kpi` VALUES ('17', '7月6日', 'success', '193');
INSERT INTO `kpi` VALUES ('18', '7月6日', 'fail', '274');
INSERT INTO `kpi` VALUES ('19', '7月7日', 'success', '232');
INSERT INTO `kpi` VALUES ('20', '7月7日', 'fail', '234');

-- ----------------------------
-- Table structure for `kpi_detail`
-- ----------------------------
DROP TABLE IF EXISTS `kpi_detail`;
CREATE TABLE `kpi_detail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `startTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `endTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `state` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of kpi_detail
-- ----------------------------
INSERT INTO `kpi_detail` VALUES ('1', '2016-07-17 16:02:19', '2016-07-17 16:02:19', 'success');
INSERT INTO `kpi_detail` VALUES ('2', '2016-07-17 16:03:27', '2016-07-17 16:03:27', 'success');
INSERT INTO `kpi_detail` VALUES ('3', '2016-07-17 16:03:27', '2016-07-17 16:03:27', 'success');
INSERT INTO `kpi_detail` VALUES ('4', '2016-07-17 16:03:27', '2016-07-17 16:03:27', 'success');
INSERT INTO `kpi_detail` VALUES ('6', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('7', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('8', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('9', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('13', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('14', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('15', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('16', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('17', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('18', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('19', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('20', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('28', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('29', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('30', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('31', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('32', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('33', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('34', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('35', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('36', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('37', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('38', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('39', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');
INSERT INTO `kpi_detail` VALUES ('40', '2016-07-17 16:03:28', '2016-07-17 16:03:28', 'success');

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'samtest', '123456');
至此,整个项目算是搭建并测试成功
附件: 项目下载