Spring4.0+Hibernate4.0+Struts2.3整合包括增删改查案例,解决整合中出现的异常

时间:2024-03-24 16:03:26

源码下载:http://download.csdn.net/detail/cmcc_1234/7034775

======================Application.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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

<!-- 自动扫描所有注解该路径 -->  
    <context:component-scan base-package="com.s4s2h4.*" />
    
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
            value="com.microsoft.sqlserver.jdbc.SQLServerDriver">
        </property>
        <property name="url"
            value="jdbc:sqlserver://192.168.1.157;instanceName=eqmis;DatabaseName=db_easyui">
        </property>
        <property name="username" value="sa"></property>
        <property name="password" value="1.0"></property>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.SQLServerDialect
                </prop>
                <!--Spring 3.x 对 Hibernate 4.x 不提供 HibernateDaoSupport,所以在dao的实现层注入SessionFactory -->
                  <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                
                <!--注意:Spring3.x不能为thread,否则报错:org.hibernate.HibernateException: save is not valid without active transaction ,
                以上配置在 增加、删除、修改 操作时,都能正确执行,事务也正常执行!
                当执行 查询 操作时,不需要事务的支持,问题来了,报错:org.hibernate.HibernateException: No Session found for current thread
                意思是必须在transcation.isActive()条件下才能执行,
                可以解决办法是:当方法不需要事务支持的时候,使用 Session session = sessionFactory.openSession()来获得Session对象,问题解决!
                 -->
                <!-- <prop key="hibernate.current_session_context_class">thread</prop>  -->
                
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/s4s2h4/services/entity/Down.hbm.xml</value>
                <value>com/s4s2h4/services/entity/Menu.hbm.xml</value>
            </list>
        </property>
    </bean>
    
     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- 事物通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="sav*" propagation="REQUIRED" rollback-for="Exception"/> <!-- rollback-for回滚事物,果存在一个事务,则支持当前事务。如果没有事务则开启  -->
            <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="upd*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="qry*" propagation="NOT_SUPPORTED" read-only="true"/>
            <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true"/>
        </tx:attributes>  
    </tx:advice>
    <!-- 事物切入 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="cut"
            expression="execution(* com.s4s2h4.services.impl.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="cut" />
    </aop:config>
   
    </beans>

======================web.xml================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
      </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
</web-app>

============================dao=============================
package com.s4s2h4.dao.impl;

import java.util.List;

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.s4s2h4.dao.BaseDao;

@Repository("BaseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {

// Spring 3.x 对 Hibernate 4.x 不提供
    // HibernateDaoSupport,所以在dao的实现层注入SessionFactory
    private SessionFactory sessionFactory;

@Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();// 增删改使用的session
    }

public Session qryCurrentSesion() {
        return sessionFactory.openSession();// 查询使用的session
    }

@SuppressWarnings("unchecked")
    public List<T> qryInfo(String hql) {
        return this.qryCurrentSesion().createQuery(hql).list();
    }

@SuppressWarnings("unchecked")
    public List<T> qryInfo(String hql, Object[] param) {
        Query qry = this.qryCurrentSesion().createQuery(hql);
        setQueryParams(qry, param);
        return qry.list();
    }

public void Delete(T cls) {

// 把脱管实例的状态复制到新实例,否则有时异常:illegally attempted to associate a proxy with
        // two open Sessions
        Object obj = this.getCurrentSession().merge(cls);
        this.getCurrentSession().delete(obj);
    }

public void upd(T cls) {
        this.getCurrentSession().update(cls);
    }

public void add(T cls) {
        this.getCurrentSession().saveOrUpdate(cls);
    }

public void setQueryParams(Query qry, Object[] params) {
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                qry.setParameter(i, params[i]);
            }
        }
    }

}

===========================Services===========================
package com.s4s2h4.services.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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

import com.s4s2h4.dao.BaseDao;
import com.s4s2h4.services.TestServices;
import com.s4s2h4.services.entity.Down;

@Service("TestServices")
public class TestServicesImpl implements TestServices {

@SuppressWarnings("rawtypes")
    @Autowired
    private BaseDao baseDao;

@SuppressWarnings("unchecked")
    public List<Down> qryKcsp() {
        return baseDao.qryInfo("from Down");
    }

@SuppressWarnings("unchecked")
    public String del(String result) {
        try {
            Down down = (Down) baseDao.qryInfo("from Down where aguid=?",
                    new Object[] { result }).get(0);
            baseDao.Delete(down);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

@SuppressWarnings("unchecked")
    public void add(Down down) {
        Down d = new Down();
        d.setAguid(UUID.randomUUID().toString());
        d.setAname(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()));
        baseDao.add(d);
    }

@SuppressWarnings("unchecked")
    public void upd(Down down) {
        Down down2 = (Down) baseDao.qryInfo("from Down where aguid=?",
                new Object[] { down.getAguid() });
        down2.setAname(down.getAname());
        baseDao.upd(down2);
    }
}

===========================action=============================
package com.s4s2h4.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.s4s2h4.services.TestServices;
import com.s4s2h4.services.entity.Down;

public class TestAction extends ActionSupport implements ServletRequestAware {
    @Autowired
    TestServices testServices;
    List<Down> downs = new ArrayList<Down>();
    private HttpServletRequest request;

String result = "";

public String qry() {
        downs = testServices.qryKcsp();
        return SUCCESS;
    }

public String add() {
        downs = testServices.qryKcsp();
        testServices.add(null);
        return SUCCESS;
    }

public String del() {
        result = testServices.del(result);// "{'id':1}";
        return SUCCESS;
    }

public List<Down> getDowns() {
        return downs;
    }

public void setDowns(List<Down> downs) {
        this.downs = downs;
    }

public String getResult() {
        return result;
    }

public void setResult(String result) {
        this.result = result;
    }

public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

public HttpServletRequest getRequest() {
        return request;
    }

public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

}

=========================struts.xml========================
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
    <struts>
        <package name="test" extends="struts-default">
            <action name="index" class="com.s4s2h4.action.TestAction" method="qry">
                <result name="success">/index.jsp</result>
            </action>
            
            <action name="add" class="com.s4s2h4.action.TestAction" method="add">
                <result name="success" type="redirect">/</result>
            </action>
            
        </package>
        
        <!-- struts json-->
        <package name="ajax" extends="json-default" >
             <action name="del" class="com.s4s2h4.action.TestAction" method="del">
                <result type="json">
                     <param name="root">result</param>
                </result>
            </action>
         </package>
    </struts>

============================jsp===============

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%String path=request.getContextPath();%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery.1.4.2-min.js"></script>
<script type="text/javascript" src="index.js" charset="gbk"></script>
</head>

<body>
    <a href="add">添加</a>
    <s:iterator value="downs">
        <li>
            <s:property value="aname" />
            <a href="javascript:delinfo('<s:property value="aguid" />')">删除</a>
        </li>
    </s:iterator>
</body>
</html>

=========================js=========================
function delinfo(aguid){
    $.ajax({
        type:"post",
        url:"s4s2h4/del",
        data:"result="+aguid,
        success:function(msg){
            if(msg=="success"){
                window.location.href=window.location.href;
            }else{
                alert("删除失败:"+msg);
            }
        }
        ,error:function(){
            alert("error");
        }
    });
}