-1

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

网页.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);
        }
    }
}

和休眠实用程序..

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);   
          }
    }

}

我正在讨论的另一种方法是在链接上另一种集成方法现在请告诉我哪种方法最好,还有比这两种方法更好的方法吗?

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

4

1 回答 1

1

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

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

最后,您可能想先更好地了解 Struts2、Hibernate 和 Spring,然后再尝试将它们全部堆起来。

于 2012-07-31T18:29:11.033 回答