Spring4Mvc整合Hibernate4框架示例

阅读更多
今天用NetBeans8.1搭建了一套Spring4MVC+Hibernate4+PostgreSQL的基础框架,这套框架需要JDK1.7和Tomcat8.0.30。

第一步:在PostgreSQL9.5里建两张数据表,笔者这里在实际框架中只用到了一个,因为对PostgreSQL还不是很熟悉,所以没做分页存储过程,笔者这里的PostgreSQL表中的主键id用的是sequence序列自动增长的。
Spring4Mvc整合Hibernate4框架示例_第1张图片

第二步:开始搭建Spring4+Hibernate4框架。
先看一下工程结构图:
Spring4Mvc整合Hibernate4框架示例_第2张图片
Spring4Mvc整合Hibernate4框架示例_第3张图片
Spring4Mvc整合Hibernate4框架示例_第4张图片
Spring4Mvc整合Hibernate4框架示例_第5张图片
Spring4Mvc整合Hibernate4框架示例_第6张图片
Spring4Mvc整合Hibernate4框架示例_第7张图片

下面是工程中所有的配置文件代码:

web.xml文件代码如下:


    
    shihuan
	
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
          encoding
          UTF-8
        
        
          forceEncoding
          true
        
    
    
        CharacterEncodingFilter
        *.do
    
    
    
        webAppRootKey
        webvip.shihuan.root
    
    
        org.springframework.web.util.WebAppRootListener
    

    
            logbackConfigLocation
            classpath:logback.xml
    
    
            ch.qos.logback.ext.spring.web.LogbackConfigListener
    
    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
            org.springframework.web.util.IntrospectorCleanupListener
    
    
    
        com.shihuan.webss.SystemLoadListener
    
    
    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
           
            contextConfigLocation   
            classpath:dispatcher-servlet.xml   
        
        1
    
    
        dispatcher
        *.do
    
    
        
            60
        
    
    
        redirect.jsp  
        
    



applicationContext.xml文件代码:



    
    
    

    
    

    
    
    
        
        
              
                org.hibernate.dialect.PostgreSQLDialect  
                true  
                true  
                org.springframework.orm.hibernate4.SpringSessionContext  
            
        
        
        
    
    
    
    
    
            
    

    
            
    



dispatcher-servlet.xml文件代码:




    
    
    
    
    

    
    
    
    
        
        
            
            
            
        
        
    
    
    
        
            
                
                
                
            
        
        
            
                
                
                    
                    
                
            
        
        
            
                
            
        
    
    
    
        
    
    

    
    

    
	
    
        
            
                500
            
        
        
        
        
        
            
                404
                500
            
        
    




jdbc.properties文件代码:
jdbc_driverClassName=org.postgresql.Driver
jdbc_url=jdbc:postgresql://127.0.0.1:5432/postgres
jdbc_username=postgres
jdbc_password=postgres


logback.xml文件代码:

	
	
	

	

	

	
		${logDir}${Project_Name}/Out${Project_Name}.log
		 
			${archivesDirectory}${Project_Name}/Out/${Project_Name}-%d{yyyy-MM-dd}.%i.zip
			
				10MB
			
		
		
			${outFormat}
		
	
        
	
		${logDir}${Project_Name}/Error${Project_Name}.log
		 
			${archivesDirectory}${Project_Name}/Error/${Project_Name}-%d{yyyy-MM-dd}.%i.zip
			
				10MB
			
		
		
			${outFormat}
		
		
			
				
				level>=40000
			
			ACCEPT
			DENY
		
	

	
		
			${outFormat}
		
	
	
		
			
				
				message.startsWith("fatal:")
			
			ACCEPT
			DENY
		
		192.168.100.111
		
		
		[email protected]
		${Project_Name}
		${Project_Name}Error: %logger{20} - %m
		
			${outFormat}
		
	
	
	
		
		
		
		
		
	



下面介绍主要java代码,部分细节代码就不做详细介绍了,读者需要自己做参考。

SystemLoadListener.java代码如下:
package com.shihuan.webss;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author shihuan
 */
public class SystemLoadListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
    protected static Logger logger = LoggerFactory.getLogger(SystemLoadListener.class);
	//参数
    private HttpServletRequest request;
    private ServletContext sc;

    // Public constructor is required by servlet spec
    public SystemLoadListener() {
    	
    }
	
    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------
	@Override
	public void attributeAdded(HttpSessionBindingEvent sbe) {
		/* This method is called when an attribute 
	        is added to a session.
	     */
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent sbe) {
		/* This method is called when an attribute
	        is removed from a session.
	     */
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent sbe) {
		/* This method is invoked when an attibute
	        is replaced in a session.
	     */
	}

	// -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
	@Override
	public void sessionCreated(HttpSessionEvent se) {
//		System.out.println("shihuan11: session创建了!!!!!!" + se.getSession().getId());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		/* Session is destroyed. */
		//TODO 调用authService
//		System.out.println("shihuan22: session过期了!!!!!!" + se.getSession().getId());
	}
	
	public void requestDestroyed(ServletRequestEvent srd) {

    }

    public void requestInitialized(ServletRequestEvent sri) {
        request = (HttpServletRequest)sri.getServletRequest();
    }

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		/* This method is invoked when the Servlet Context 
	        (the Web application) is undeployed or 
	        Application Server shuts down.
	     */
	}

	// -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
		ServletContext context = sce.getServletContext();
        //取得appliction上下文
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        context.setAttribute("ac", ctx);
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);
        context.setAttribute("wac", wac);
        context.setAttribute("currequest", request);
    }
}


OpMessage.java文件代码:
package com.shihuan.web.page;

/**
 *
 * @author shihuan
 */
public class OpMessage {
    /**
    * @param success
    *  true 表示成功, false 表示失败
    * @param message
    */
   public OpMessage(boolean success, String message) {
           this.success = success;
           this.message = message;
           this.logResult = message;
   }

   public OpMessage(boolean success, String message, Object infoObj) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.infoObj=infoObj;
   }

   public OpMessage(boolean success, String message, java.io.Serializable poID) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.poID = poID;
   }
   public OpMessage(boolean success, String message, java.io.Serializable poID, Object infoObj) {
           this.success = success;
           this.message = message;
           this.logResult = message;
           this.poID = poID;
           this.infoObj=infoObj;
   }

   public OpMessage(boolean success, Exception ex) {
           this.success = success;
           this.message = ex.getMessage();
           this.logResult = ex.getMessage();
   }

   /**
    * 表示是否成功
    */
   private boolean success;
   /**
    * 表示返回信息
    */
   private String message;

   /**
    * 错误信息
    */
   private String logResult;

   /**
    * PK
    */
   java.io.Serializable poID;

   //作为返回信息
   private Object infoObj;

   public Object getInfoObj() {
           return infoObj;
   }

   public void setInfoObj(Object infoObj) {
           this.infoObj = infoObj;
   }

   public boolean getSuccess() {
           return success;
   }

   public void setSuccess(boolean success) {
           this.success = success;
   }

   public String getMessage() {
           return message;
   }

   public void setMessage(String message) {
           this.message = message;
   }

   public java.io.Serializable getPoID() {
           return poID;
   }

   public void setPoID(java.io.Serializable poID) {
           this.poID = poID;
   }

   public String getLogResult() {
           return logResult;
   }

   public void setLogResult(String logResult) {
           this.logResult = logResult;
   }
   public OpMessage(){

   }

   public static OpMessage getInstance(){
           return new OpMessage();
   }
   public OpMessage setOPSuccess(boolean isSuccess){
           this.setSuccess(isSuccess);
           return this;
   }
   public OpMessage setOPMessage(String msg){
           this.setMessage(msg);
           return this;
   }
   public OpMessage setOPPoID(java.io.Serializable msg){
           this.setPoID(msg);
           return this;
   }
   public OpMessage setOPInfoObj(Object infoObj){
           this.setInfoObj(infoObj);
           return this;
   }
   public OpMessage setOPLogResult(String logResult){
           this.setLogResult(logResult);
           return this;
   }
}


TestPgDao.java代码如下:
package com.shihuan.web.dao;

import java.util.Map;

/**
 *
 * @author shihuan
 */
public interface TestPgDao {
    public void insertData(Map params);
    public void updateData(Map params);
    public void queryData(Map params);
    public void deleteData(Map params);
}


TestPgDaoImpl.java代码如下:
package com.shihuan.web.dao.impl;

import com.shihuan.web.dao.TestPgDao;
import com.shihuan.web.util.UserHibernateDao;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

/**
 *
 * @author shihuan
 */
@Repository
public class TestPgDaoImpl extends UserHibernateDao implements TestPgDao {

    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    @Override
    public void insertData(Map params) {
        String sql = "insert into company(name,age,address,salary) values (?,?,?,?)";
        Object[] objparams = new Object[4];
        objparams[0] = params.get("name");
        objparams[1] = Integer.parseInt(params.get("age").toString());
        objparams[2] = params.get("address");
        objparams[3] = Double.parseDouble(params.get("salary").toString());
        
        batchExecuteByArrs(sql, objparams);
    }

    @Override
    public void updateData(Map params) {
        String sql = "update company set name=? where id=?";
        batchExecuteByMulti(sql, "大家好", 1);
    }

    @Override
    public void queryData(Map params) {
        String sql = "select id,name,age,address,salary from company";
        
    }

    @Override
    public void deleteData(Map params) {
        String sql = "delete from company where id=2";
        
    }
    
}


TestPgService.java代码如下:
package com.shihuan.web.service;

import java.util.Map;

/**
 *
 * @author shihuan
 */
public interface TestPgService {
    public void insertData(Map params);
    public void updateData(Map params);
    public void queryData(Map params);
    public void deleteData(Map params);
}


TestPgServiceImpl.java代码如下:
package com.shihuan.web.service.impl;

import com.shihuan.web.dao.TestPgDao;
import com.shihuan.web.service.TestPgService;
import java.util.Map;

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

/**
 *
 * @author shihuan
 */
@Service
public class TestPgServiceImpl implements TestPgService {

    @Autowired
    TestPgDao testPgDao;
    
    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void insertData(Map params) {
        testPgDao.insertData(params);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void updateData(Map params) {
        testPgDao.updateData(params);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Throwable.class)
    public void queryData(Map params) {
        testPgDao.queryData(params);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Throwable.class)
    public void deleteData(Map params) {
        testPgDao.deleteData(params);
    }
    
}


BaseControl.java代码如下:
package com.shihuan.web.controller;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 *
 * @author shihuan
 */
public abstract class BaseControl {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    protected boolean useRedirect = false;
    public static final String ENTRY_URL = "ENTRY_URL";
    
    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
        dataBinder.registerCustomEditor(Integer.class, new PropertyEditorSupport() {
            public void setAsText(String value) {
                try {
                    if (value == null || "".equals(value)) {
                        setValue(0);
                    } else {
                        setValue(Integer.parseInt(value));
                    }
                } catch (Exception e) {
                    setValue(0);
                }
            }

            public String getAsText() {
                Object obj = getValue();
                if (obj != null) {
                    return obj.toString();
                }
                return "";
            }

        });
    }

    @SuppressWarnings("rawtypes")
	public Map getParmMap(HttpServletRequest p_request) {
        HashMap map = new HashMap();
        Map orimap = p_request.getParameterMap();
        Set keys = orimap.keySet();
        for (Object key1 : keys) {
            String key = (String) key1;
            String[] value = (String[]) orimap.get(key);
            if(StringUtils.endsWith(key, "[]")){
        		key = key.substring(0, key.length()-2);
        	}
            if (value.length > 1) {
            	StringBuffer sb = new StringBuffer();
            	sb.append(" * Para : " + key + " = '[");
            	boolean firstFlag = true;
            	for(String logvalue : value){
            		if(firstFlag){
            			firstFlag = false;
            		}else{
            			sb.append(",");
            		}
            		sb.append(logvalue);
            	}
            	logger.debug(sb.toString() + "]'  * ");
                map.put(key, value);
            } else {
                logger.debug(" * Para : " + key + " = '" + value[0] + "'  * ");
                map.put(key, value[0]);
            }
        }
        return map;
    }

    /**
     * 功能: 获取当前登录用户的userid
     * */
    public int getUserid(HttpServletRequest p_request){
    	int resultid = p_request.getSession().getAttribute("curuserid")==null ? 0 : Integer.parseInt(p_request.getSession().getAttribute("curuserid").toString());
    	return resultid;
    } 
    /**
     * 功能: 获取当前登录用户的userName
     * */
    public String getUserName(HttpServletRequest p_request){
    	String resultName = p_request.getSession().getAttribute("username")==null ? "" : p_request.getSession().getAttribute("username").toString();
    	return resultName;
    }
    
    /**
     * 功能: 获取当前登录用户的公司id
     * */
    public int getOrganizationId(HttpServletRequest p_request){
    	int resultid = p_request.getSession().getAttribute("organizationid")==null ? 0 : Integer.parseInt(p_request.getSession().getAttribute("organizationid").toString());
    	return resultid;
    }
    
    //Initialize global variables
    public final void init() {
    	
    }

    //Clean up resources
    public final void destroy() {
    	
    }
}


IndexController.java代码如下:
package com.shihuan.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author shihuan
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());
    
    @RequestMapping(value = "index.do")
    public String testPgListPage(HttpServletRequest request) {
        return "appbusiness/testpg/TestPgAdd";
    }
}


TestPgController.java代码如下:
package com.shihuan.web.controller;

import com.shihuan.web.page.OpMessage;
import com.shihuan.web.service.TestPgService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author shihuan
 */
@Controller
@RequestMapping(value = "appbusiness/testpg/")
public class TestPgController extends BaseControl {
    protected Logger logger = LoggerFactory.getLogger(getClass().getName());
    
    @Autowired
    private TestPgService testPgService;
    
    @RequestMapping(value = "addCompanyMsg.do")
    @ResponseBody
    public OpMessage addCompany(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OpMessage om = null;
        try {
                Map params = getParmMap(request);
//                params.put("curuserid", getUserid(request));
                testPgService.insertData(params);
                om = new OpMessage(true, "添加公司信息成功");
        } catch (Exception e) {
                om = new OpMessage(false, "后台数据查询错误,请通知系统管理员处理。");
                logger.error(e.getMessage(), e);
                e.printStackTrace();
        }
        return om;
    }

}


SimpleHibernateDao.java文件代码太多,都是执行SQL语句的方法,这里只做结构介绍:
package com.shihuan.web.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;

import com.shihuan.config.ConfigCommon;
import com.shihuan.util.AssertUtil;
import com.shihuan.exception.SysException;


/**
 *
 * @author shihuan
 */
public abstract class SimpleHibernateDao {
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    
    public static int queryTimeout = 0;

    /**
     * 取得sessionFactory.
     */
    abstract public SessionFactory getSessionFactory();
    
    /**
     * 取得当前Session.
     */
    public Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    /**
     * 功能: insert、update或者delete一条数据
     * @param sql
     * @param params sql语句参数数组
     * @return 返回执行条数
     * */
    public int batchExecuteByArrs(String sql, Object[] params) {
    	AssertUtil.notEmptyAndNull(sql, "sql语句不允许为空");
    	SQLQuery sqlquery = getSession().createSQLQuery(sql);
    	StringBuilder sb = new StringBuilder();
		sb.append(ConfigCommon.SQLFLAG).append(sql).append(ConfigCommon.LINEFEEDFLAG).append(ConfigCommon.PARAMSFLAG);
		boolean isFirst = true;
		if(params.length > 0){
			for(int i=0; i 0){
			for(int i=0; i 
 

UserHibernateDao.java代码如下:
package com.shihuan.web.util;

import javax.annotation.Resource;
import org.hibernate.SessionFactory;

/**
 *
 * @author shihuan
 */
public class UserHibernateDao extends SimpleHibernateDao {
    @Resource(name="sessionFactory")
    protected SessionFactory sessionFactory;

    @Override
    public SessionFactory getSessionFactory() {
            return sessionFactory;
    }
}


TestPgAdd.js文件代码如下:
function addCompany() {
    if($("#name").val().trim() == ""){
            alert("姓名不允许为空!");
            $("#name").focus();
            return;
    }else{
            var url="appbusiness/testpg/addCompanyMsg.do";
            var params={"name":$("#name").val(),"age":$("#age").val(),"address":$("#address").val(),"salary":$("#salary").val()};
            $.post(url, params, function(json){
                if (json.success) {
                        alert(json.message);
                        return;
                }
            },"json");
    }
}


TestPgAdd.jsp文件代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page isELIgnored="false" %>





    
        
        TestPgAdd Company
        
        
    
    
        
姓名 年龄 地址 薪资



redirect.jsp代码如下:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("index.do"); %>


在浏览器中输入http://127.0.0.1:8080/webvip/访问工程,截图如下:
Spring4Mvc整合Hibernate4框架示例_第8张图片
数据库结果截图如下:
Spring4Mvc整合Hibernate4框架示例_第9张图片


附件webvip.rar文件是工程源代码,项目所需jar包在abcdef830619的网易邮箱网盘的我的原创目录里。
  • Spring4Mvc整合Hibernate4框架示例_第10张图片
  • 大小: 16.7 KB
  • Spring4Mvc整合Hibernate4框架示例_第11张图片
  • 大小: 7.7 KB
  • Spring4Mvc整合Hibernate4框架示例_第12张图片
  • 大小: 33.5 KB
  • Spring4Mvc整合Hibernate4框架示例_第13张图片
  • 大小: 27.5 KB
  • Spring4Mvc整合Hibernate4框架示例_第14张图片
  • 大小: 24.4 KB
  • Spring4Mvc整合Hibernate4框架示例_第15张图片
  • 大小: 25.4 KB
  • Spring4Mvc整合Hibernate4框架示例_第16张图片
  • 大小: 45.3 KB
  • Spring4Mvc整合Hibernate4框架示例_第17张图片
  • 大小: 40.6 KB
  • Spring4Mvc整合Hibernate4框架示例_第18张图片
  • 大小: 38 KB
  • webvip.rar (251.4 KB)
  • 下载次数: 2
  • 查看图片附件

你可能感兴趣的:(spring4,hibernate4,postgresql)