集成struts2 + spring + Hibernate

时间:2012-07-31 18:05:46

标签: spring hibernate struts2

这些天我经历了hibernate然后我正在尝试开发一个应用程序来集成struts2 + Hibernate + Spring ..我有两种初始化hibernate会话工厂的方法..当我们为struts2加载过滤器调度程序时那个时候我们应该加载hibernate sessionfactory,例如如下所示..

... Web.xml中

<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>
  <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
  <filter>
    <filter-name>controller</filter-name>
    <filter-class>mypack.Struts2Dispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>controller</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping></web-app>

Struts2Dispatcher文件..

import javax.servlet.*;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.hibernate.HibernateException;

public class Struts2Dispatcher extends FilterDispatcher
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        super.init(filterConfig);
        try
        {
            HibernateUtil.createSessionFactory();
            System.out.print("-------application initializing successfully-----");
        }
        catch (HibernateException e)
        {
            throw new ServletException(e);
        }
    }
}

和hibernate util ..

package mypack;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;

public class HibernateUtil
{
    private static SessionFactory sessionFactory;
    public static void createSessionFactory()
    {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    public static Session getSession()
    {
        return sessionFactory.openSession();
    }
}

配置文件..

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="connection.username">system</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.password">manager</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
         <property name="show_sql">true</property>
         <mapping resource="Employee.hbm.xml"/> 
    </session-factory>

</hibernate-configuration>

映射文件..

<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
          <hibernate-mapping>
          <class name="mypack.Employee">
          <id name="eid" column="emp_id" type="int">
          <generator class="increment"/></id>
          <property name="name" column="emp_name"/>
          <property name="job"/>
          <property name="salary" type="int"/>
          </class>
          </hibernate-mapping>

应用程序context.xml文件

<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="MyIOCObject" class="mypack.LoginAction"/>

</beans>

struts.xml文件..

<struts>    
<package name="pack" extends="struts-default">
<action name="login" class="MyIOCObject" method="insert">
<result name="success">/welcome.jsp</result>
<result name="failure">/relogin.jsp</result>
</action>
</package>
</struts>    

登录Action java类

package mypack;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;

public class LoginAction 
{
     private String name,job;
     private int salary;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String insert()
    {
      try
      {
        Session ses=HibernateUtil.getSession();
        Employee emp=new Employee(name,job,salary);
        Transaction tx=ses.beginTransaction();
        ses.save(emp);
        tx.commit();
        ses.close();
        return "success";
      }catch(Exception e)
      {
          System.out.println(e);
          return "failure";
      }
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

}

主要员工pojo

package mypack;

public class Employee
{
      private int eid,salary;
      private String name,job;

    public Employee() 
    {
        super();
    }

    public Employee(String name, String job,int salary)
    {
        super();
        this.salary = salary;
        this.name = name;
        this.job = job;
    }

    public int getEid() {
        return eid;
    }
    public void setEid(int eid) {
        this.eid = eid;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }

}

主要的测试程序..

package mypack;

import java.util.Scanner;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class TestProgram
{

    public static void main(String[] args)
    {
          try
          {
              Configuration cfg=new Configuration();
              cfg.configure();
              SessionFactory sesfac=cfg.buildSessionFactory();
              Session ses=sesfac.openSession();
              System.out.println("Session created , fetching objects...");
              Scanner in=new Scanner(System.in);
              System.out.println("Enter Employee id :- ");
              int id=in.nextInt();
              Employee e=(Employee)ses.load(Employee.class,id);
              System.out.println("Following Object is fetched");
              System.out.println(e.getEid()+"\t"+e.getName()+"\t"+e.getSalary()+"\t"+e.getJob());
              ses.close();

          }catch (Exception e)
          {
              System.out.println(e);   
          }
    }

}

我正在讨论的另一种方法是在链接another approach to integagrate 现在请告诉我哪种方法最好,还有其他方法比这两种方法更好吗?

请发布更新的代码,以便我能掌握这个概念,请指教.. !!

1 个答案:

答案 0 :(得分:1)

这对我有用(使用Struts2,JPA / Hibernate和Guice):

  • EntityManagerFactory中创建并销毁SessionFactoryServletContextListener;不要继承Struts2过滤器来执行此操作(另外,请考虑使用较新的StrutsPrepareAndExecuteFilter而不是较旧的,已弃用的FilterDispatcher
  • 在拦截器中创建并销毁EntityManagerSession,以便每个请求都有自己的工作单元;这是一种最佳实践,因为这些工作单元不是线程安全的,不应跨请求共享
  • 将拦截器尽早放置在堆栈中,以确保需要访问数据库的任何其他拦截器都在它之后;这采用了 Open View in View 模式,可以确保在渲染视图时(在处理完动作之后)可以获取任何延迟加载的属性。

最后,在尝试将它们全部打开之前,您可能希望先了解一下Struts2,Hibernate和Spring。