struts2+spring3.0+hibernate注解方式

来源:互联网 发布:天猫魔盒投屏软件 编辑:程序博客网 时间:2024/05/18 01:25

最近用这三个东西开发了一个后台管理的程序,现在写出来希望能够讨论谈论,因为我刚开始弄有很多东西都还不知道,在这里写出来望大家发现到问题后能够给我留言,以便完善,呵呵~

第一步:导入工程需要的包,具体需要哪些包,如果有需要的话我可以提供,当然最好的就是去官网下载了,呵呵~

第二步:配置web.xml文件。我的web.xml文件如下:

view plaincopy to clipboardprint?
<?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">  
    <!-- 默认i18n资源文件 -->  
    <context-param>  
        <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>  
        <param-value>i18n/messages</param-value>  
    </context-param>  
      
    <!--  
        Location of the Log4J config file, for initialization and refresh checks.  
        Applied by Log4jConfigListener.  
    -->  
    <context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>/WEB-INF/classes/log4j.properties</param-value>  
    </context-param>  
      
    <filter>  
        <filter-name>struts2</filter-name>  
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
        <init-param>  
            <param-name>actionPackages</param-name>  
            <param-value>com.cssweb.tradeadmin.action.trade</param-value>  
        </init-param>  
    </filter>  
 
    <filter-mapping>  
        <filter-name>struts2</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
      
    <!-- 著名 Character Encoding filter -->  
    <filter>  
        <filter-name>encodingFilter</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>  
    </filter>  
 
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/WEB-INF/applicationContext.xml</param-value>  
    </context-param>  
 
    <!-- Spring 刷新Introspector防止内存泄露 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  
      
    <session-config>  
        <session-timeout>30</session-timeout>  
    </session-config>  
      
    <!-- Error Page定义 -->  
    <error-page>  
        <error-code>500</error-code>  
        <location>/commons/error.jsp</location>  
    </error-page>  
    <error-page>  
        <error-code>404</error-code>  
        <location>/commons/404.jsp</location>  
    </error-page>  
    <error-page>  
        <error-code>403</error-code>  
        <location>/commons/403.jsp</location>  
    </error-page>  
      
    <welcome-file-list>  
        <!-- Redirects to "welcome.htm" for dispatcher handling -->  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
   
</web-app> 
<?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">
 <!-- 默认i18n资源文件 -->
 <context-param>
  <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
  <param-value>i18n/messages</param-value>
 </context-param>
 
    <!--
        Location of the Log4J config file, for initialization and refresh checks.
        Applied by Log4jConfigListener.
    -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>
   
 <filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  <init-param>
   <param-name>actionPackages</param-name>
   <param-value>com.cssweb.tradeadmin.action.trade</param-value>
  </init-param>
 </filter>

 <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <!-- 著名 Character Encoding filter -->
 <filter>
  <filter-name>encodingFilter</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>
 </filter>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

 <!-- Spring 刷新Introspector防止内存泄露 -->
 <listener>
  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>
   
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
 
 <!-- Error Page定义 -->
 <error-page>
  <error-code>500</error-code>
  <location>/commons/error.jsp</location>
 </error-page>
 <error-page>
  <error-code>404</error-code>
  <location>/commons/404.jsp</location>
 </error-page>
 <error-page>
  <error-code>403</error-code>
  <location>/commons/403.jsp</location>
 </error-page>
 
    <welcome-file-list>
        <!-- Redirects to "welcome.htm" for dispatcher handling -->
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
 
</web-app>
 

第三步:配置strust.xml文件(由于我用的是注解驱动方式,所以只有这一个文件)

view plaincopy to clipboardprint?
<?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>  
        <constant name="struts.custom.i18n.resources" value="globalMessages" />  
        <constant name="struts.convention.package.locators" value="action" />   
        <constant name="struts.i18n.encoding" value="UTF-8" />  
        <!-- when you used to real please set false -->  
        <constant name="struts.devMode" value="true" />  
        <!-- 将struts2委托Spring管理 -->  
        <constant name="struts.objectFactory" value="spring" />   
          
        <package name="mydefault" extends="struts-default">  
              
            <global-results>  
                <!-- 下面定义的结果对所有的Action都有效 -->  
                <result name="exception">/commons/error.jsp</result>  
                <result name="login">/login/login.jsp</result>  
            </global-results>  
 
            <global-exception-mappings>  
                <!-- 指Action抛出Exception异常时,转入名为exception的结果。 -->  
                <exception-mapping exception="java.lang.Exception" result="exception"/>  
            </global-exception-mappings>  
        </package>   
           
</struts> 
<?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>
        <constant name="struts.custom.i18n.resources" value="globalMessages" />
     <constant name="struts.convention.package.locators" value="action" />
        <constant name="struts.i18n.encoding" value="UTF-8" />
        <!-- when you used to real please set false -->
        <constant name="struts.devMode" value="true" />
        <!-- 将struts2委托Spring管理 -->
      <constant name="struts.objectFactory" value="spring" />
    
        <package name="mydefault" extends="struts-default">
   
      <global-results>
       <!-- 下面定义的结果对所有的Action都有效 -->
       <result name="exception">/commons/error.jsp</result>
       <result name="login">/login/login.jsp</result>
      </global-results>

      <global-exception-mappings>
       <!-- 指Action抛出Exception异常时,转入名为exception的结果。 -->
       <exception-mapping exception="java.lang.Exception" result="exception"/>
      </global-exception-mappings>
        </package>
        
</struts>
 

第四步:配置spring的xml文件包含hibernate的引入

view plaincopy to clipboardprint?
<?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:context="http://www.springframework.org/schema/context" 
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">  
      
    <context:component-scan base-package="com.cssweb.tradeadmin.action"/>  
      
    <bean id="propertyConfigurer" 
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
          p:location="/WEB-INF/jdbc.properties" />  
      
    <bean id="dataSource" 
          class="org.springframework.jdbc.datasource.DriverManagerDataSource" 
          p:driverClassName="${jdbc.driverClassName}" 
          p:url="${jdbc.url}" 
          p:username="${jdbc.username}" 
          p:password="${jdbc.password}" />  
      
    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->  
    <!-- Hibernate SessionFactory -->  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" 
                p:dataSource-ref="dataSource">  
        <property name="hibernateProperties">  
                <props>  
                        <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                        <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>  
                </props>  
        </property>  
        <property name="mappingResources">  
                <list>  
                    <value>com/cssweb/tradeadmin/model/UserBasicInfo.hbm.xml</value>  
                    <value>com/cssweb/tradeadmin/model/LogLoginToday.hbm.xml</value>  
                    <value>com/cssweb/tradeadmin/model/CustHostInfo.hbm.xml</value>  
            </list>  
        </property>  
        <property name="eventListeners">  
                <map>  
                        <entry key="merge">  
                                <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>  
                        </entry>  
                </map>  
        </property>  
    </bean>  
 
    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->  
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
                p:sessionFactory-ref="sessionFactory"/>  
 
    <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->  
    <!--  
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>  
    -->  
 
 
    <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->  
 
    <!--  
        Activates various annotations to be detected in bean classes:  
        Spring's @Required and @Autowired, as well as JSR 250's @Resource.  
    -->  
    <context:annotation-config/>  
 
    <!--  
        Instruct Spring to perform declarative transaction management  
        automatically on annotated classes.  
    -->  
    <tx:annotation-driven/>  
 
    <!--  
        Exporter that exposes the Hibernate statistics service via JMX. Autodetects the  
        service MBean, using its bean name as JMX object name.  
    -->  
    <context:mbean-export/>  
      
      
    <aop:aspectj-autoproxy/>  
 
    <!-- PetClinic's central data access object: Hibernate implementation -->  
    <bean id="clinic" class="com.cssweb.tradeadmin.dao.hibernate.HibernateClinic"/>  
</beans> 
<?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:context="http://www.springframework.org/schema/context"
  xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
   
    <context:component-scan base-package="com.cssweb.tradeadmin.action"/>
   
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />
   
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}" />
   
    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
                p:dataSource-ref="dataSource">
        <property name="hibernateProperties">
                <props>
                        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                        <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                </props>
        </property>
        <property name="mappingResources">
          <list>
           <value>com/cssweb/tradeadmin/model/UserBasicInfo.hbm.xml</value>
           <value>com/cssweb/tradeadmin/model/LogLoginToday.hbm.xml</value>
           <value>com/cssweb/tradeadmin/model/CustHostInfo.hbm.xml</value>
         </list>
        </property>
        <property name="eventListeners">
                <map>
                        <entry key="merge">
                                <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener"/>
                        </entry>
                </map>
        </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
                p:sessionFactory-ref="sessionFactory"/>

    <!-- Transaction manager that delegates to JTA (for a transactional JNDI DataSource) -->
    <!--
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
    -->


    <!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

    <!--
        Activates various annotations to be detected in bean classes:
        Spring's @Required and @Autowired, as well as JSR 250's @Resource.
    -->
    <context:annotation-config/>

    <!--
        Instruct Spring to perform declarative transaction management
        automatically on annotated classes.
    -->
    <tx:annotation-driven/>

    <!--
        Exporter that exposes the Hibernate statistics service via JMX. Autodetects the
        service MBean, using its bean name as JMX object name.
    -->
    <context:mbean-export/>
   
   
    <aop:aspectj-autoproxy/>

    <!-- PetClinic's central data access object: Hibernate implementation -->
    <bean id="clinic" class="com.cssweb.tradeadmin.dao.hibernate.HibernateClinic"/>
</beans>


第五步:在action包里面建action类:

view plaincopy to clipboardprint?
/** 
 * Copyright 2010 CssWeb Microsystems, Inc. All rights reserved. 
 * CssWeb PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 
 * 
 * @(#)LoginAction.java 1:58:01 PM Apr 15, 2010 
 */ 
package com.cssweb.tradeadmin.action;  
 
import java.util.List;  
import java.util.Map;  
 
import javax.servlet.http.HttpServletRequest;  
 
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.apache.struts2.ServletActionContext;  
import org.apache.struts2.convention.annotation.Action;  
import org.apache.struts2.convention.annotation.Namespace;  
import org.apache.struts2.convention.annotation.ParentPackage;  
import org.apache.struts2.convention.annotation.Result;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
 
import com.cssweb.common.exception.BussinessException;  
import com.cssweb.common.util.MD5;  
import com.cssweb.tradeadmin.dao.Clinic;  
import com.cssweb.tradeadmin.model.UserBasicInfo;  
import com.opensymphony.xwork2.ActionContext;  
import com.opensymphony.xwork2.ActionSupport;  
 
/** 
 * 交易系统后台登录 
 * 
 * @author hujun 
 * @version 1.0 
 * @see 
 * @since 1.0 
 */ 
@Controller 
@ParentPackage("mydefault")   
@Namespace("/user")  
@Scope("prototype")  
public class LoginAction extends ActionSupport {  
    /** 
     *  
     */ 
    private static final long serialVersionUID = 7454734463309586123L;  
 
    private Log log = LogFactory.getLog(LoginAction.class);  
      
    private final Clinic clinic;  
      
    private String loginName;  
    private String loginPwd;  
    private String incode;  
      
    @Autowired 
    public LoginAction(Clinic clinic) {  
        this.clinic = clinic;  
    }  
      
    @Action(value="login",   
            results={@Result(name="success", location="/index.jsp", type="redirect"),  
                     @Result(name="input", location="/login/login.jsp")})  
    public String login() {  
        System.out.println(">>>>>>>>>>>>>>>>>>>>" + loginName);  
        System.out.println(">>>>>>>>>>>>>>>>>>>>" + loginPwd);  
        System.out.println(">>>>>>>>>>>>>>>>>>>>" + incode);  
        String msg = "";  
        try {  
            Map session = ActionContext.getContext().getSession();  
            String vnum = (String)session.get("vnum");  
            if(vnum!=null&&!vnum.toLowerCase().equals(incode.toLowerCase())) {  
                msg="验证码不正确!";  
            }  
            else {  
                MD5 md5 = new MD5();  
                UserBasicInfo user = new UserBasicInfo();  
                user.setUserName(loginName);  
                user.setPassword(md5.getMD5ofStr(loginPwd));  
                List<?> list = this.clinic.queryList(user, 0, 1, null, false);  
                if(list!=null&&list.size()>0) {  
                    session.put("userName", loginName);  
                    session.put("password", loginPwd);  
                }  
                else {  
                    msg="用户和密码不正确!";  
                }  
            }  
            HttpServletRequest request = ServletActionContext.getRequest();  
            request.setAttribute("msg", msg);  
        } catch (BussinessException e) {  
            log.error(e);  
        }  
        System.out.println(">>>>>>>>>>>>##########" + msg);  
        return msg.equals("") ? SUCCESS : "input";  
    }  
 
    public String getLoginName() {  
        return loginName;  
    }  
 
    public void setLoginName(String loginName) {  
        this.loginName = loginName;  
    }  
 
    public String getLoginPwd() {  
        return loginPwd;  
    }  
 
    public void setLoginPwd(String loginPwd) {  
        this.loginPwd = loginPwd;  
    }  
 
    public String getIncode() {  
        return incode;  
    }  
 
    public void setIncode(String incode) {  
        this.incode = incode;  
    }  

/**
 * Copyright 2010 CssWeb Microsystems, Inc. All rights reserved.
 * CssWeb PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * @(#)LoginAction.java 1:58:01 PM Apr 15, 2010
 */
package com.cssweb.tradeadmin.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cssweb.common.exception.BussinessException;
import com.cssweb.common.util.MD5;
import com.cssweb.tradeadmin.dao.Clinic;
import com.cssweb.tradeadmin.model.UserBasicInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 交易系统后台登录
 *
 * @author hujun
 * @version 1.0
 * @see
 * @since 1.0
 */
@Controller
@ParentPackage("mydefault")
@Namespace("/user")
@Scope("prototype")
public class LoginAction extends ActionSupport {
 /**
  *
  */
 private static final long serialVersionUID = 7454734463309586123L;

 private Log log = LogFactory.getLog(LoginAction.class);
 
    private final Clinic clinic;
   
    private String loginName;
    private String loginPwd;
    private String incode;
   
    @Autowired
    public LoginAction(Clinic clinic) {
        this.clinic = clinic;
    }
   
    @Action(value="login",
      results={@Result(name="success", location="/index.jsp", type="redirect"),
         @Result(name="input", location="/login/login.jsp")})
    public String login() {
     System.out.println(">>>>>>>>>>>>>>>>>>>>" + loginName);
     System.out.println(">>>>>>>>>>>>>>>>>>>>" + loginPwd);
     System.out.println(">>>>>>>>>>>>>>>>>>>>" + incode);
     String msg = "";
     try {
      Map session = ActionContext.getContext().getSession();
      String vnum = (String)session.get("vnum");
      if(vnum!=null&&!vnum.toLowerCase().equals(incode.toLowerCase())) {
       msg="验证码不正确!";
      }
      else {
          MD5 md5 = new MD5();
             UserBasicInfo user = new UserBasicInfo();
             user.setUserName(loginName);
             user.setPassword(md5.getMD5ofStr(loginPwd));
       List<?> list = this.clinic.queryList(user, 0, 1, null, false);
       if(list!=null&&list.size()>0) {
        session.put("userName", loginName);
        session.put("password", loginPwd);
       }
       else {
        msg="用户和密码不正确!";
       }
      }
      HttpServletRequest request = ServletActionContext.getRequest();
      request.setAttribute("msg", msg);
  } catch (BussinessException e) {
   log.error(e);
  }
  System.out.println(">>>>>>>>>>>>##########" + msg);
     return msg.equals("") ? SUCCESS : "input";
    }

 public String getLoginName() {
  return loginName;
 }

 public void setLoginName(String loginName) {
  this.loginName = loginName;
 }

 public String getLoginPwd() {
  return loginPwd;
 }

 public void setLoginPwd(String loginPwd) {
  this.loginPwd = loginPwd;
 }

 public String getIncode() {
  return incode;
 }

 public void setIncode(String incode) {
  this.incode = incode;
 }
}

第六步:hibernate类,在这里action中的Clinic是接口,hibernate类集成这个接口

view plaincopy to clipboardprint?
@Autowired 
private SessionFactory sessionFactory;  
 
   /** 
    * 保存(新建或者更新) 
    */ 
   public void merge(Object obj) throws BussinessException {  
       try {  
           Session session = sessionFactory.openSession();  
           Transaction t=session.beginTransaction();  
           session.merge(obj);  
           t.commit();  
       }catch(RuntimeException e){  
        log.error(e);  
        throw new BussinessException(e);  
       }  
   }  
     
   /** 
    * 保存(新建或者更新) 
    */ 
   public void save(Object obj) throws BussinessException {  
       try {  
           Session session = sessionFactory.openSession();  
           Transaction t=session.beginTransaction();  
           session.save(obj);  
           t.commit();  
       }catch(RuntimeException e){  
        log.error(e);  
        throw new BussinessException(e);  
       }  
   }  
     
   /** 
    * 保存(新建或者更新) 
    */ 
   public void update(Object obj) throws BussinessException {  
       try {  
           Session session = sessionFactory.openSession();  
           Transaction t=session.beginTransaction();  
           session.update(obj);  
           t.commit();  
       }catch(RuntimeException e){  
        log.error(e);  
        throw new BussinessException(e);  
       }  
   }  
   /** 
    * 保存(新建或者更新) 
    */ 
   public void saveOrupdate(Object obj) throws BussinessException {  
       try {  
           Session session = sessionFactory.openSession();  
           Transaction t=session.beginTransaction();  
           session.saveOrUpdate(obj);  
           t.commit();  
       }catch(RuntimeException e){  
        log.error(e);  
        throw new BussinessException(e);  
       }  
   } 
 @Autowired
 private SessionFactory sessionFactory;
 
    /**
     * 保存(新建或者更新)
     */
    public void merge(Object obj) throws BussinessException {
        try {
            Session session = sessionFactory.openSession();
            Transaction t=session.beginTransaction();
            session.merge(obj);
            t.commit();
        }catch(RuntimeException e){
         log.error(e);
         throw new BussinessException(e);
        }
    }
   
    /**
     * 保存(新建或者更新)
     */
    public void save(Object obj) throws BussinessException {
        try {
            Session session = sessionFactory.openSession();
            Transaction t=session.beginTransaction();
            session.save(obj);
            t.commit();
        }catch(RuntimeException e){
         log.error(e);
         throw new BussinessException(e);
        }
    }
   
    /**
     * 保存(新建或者更新)
     */
    public void update(Object obj) throws BussinessException {
        try {
            Session session = sessionFactory.openSession();
            Transaction t=session.beginTransaction();
            session.update(obj);
            t.commit();
        }catch(RuntimeException e){
         log.error(e);
         throw new BussinessException(e);
        }
    }
    /**
     * 保存(新建或者更新)
     */
    public void saveOrupdate(Object obj) throws BussinessException {
        try {
            Session session = sessionFactory.openSession();
            Transaction t=session.beginTransaction();
            session.saveOrUpdate(obj);
            t.commit();
        }catch(RuntimeException e){
         log.error(e);
         throw new BussinessException(e);
        }
    }

由于部分代码设计到公司正在运营的项目,所以不能贴出忘大家原谅!另外如果大家对这块比较感兴趣的话希望可以多交流交流,比如我这里的struts.xml文件的配置不完整,总之我把我会的都写出来希望能够给大家个参考,同时也希望高手能够指点下,呵呵~

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiaojunhu/archive/2010/04/19/5500365.aspx

原创粉丝点击