Java 集成Struts 2和hibernate的最佳方法

Java 集成Struts 2和hibernate的最佳方法,java,spring,hibernate,struts2,Java,Spring,Hibernate,Struts2,我打算集成hibernate和struts2。请告诉我哪种方法是最好的,我认为在Struts2中,没有官方插件来集成Hibernate框架。但是,您可以通过以下步骤解决问题: 注册自定义ServletContextListener 在ServletContextListener类中,初始化Hibernate会话并将其存储到servlet上下文中 在action类中,从servlet上下文获取Hibernate会话,并正常执行Hibernate任务 请告知我初始化hibernate会话功能的ser

我打算集成hibernate和struts2。请告诉我哪种方法是最好的,我认为在Struts2中,没有官方插件来集成Hibernate框架。但是,您可以通过以下步骤解决问题:

  • 注册自定义ServletContextListener
  • 在ServletContextListener类中,初始化Hibernate会话并将其存储到servlet上下文中
  • 在action类中,从servlet上下文获取Hibernate会话,并正常执行Hibernate任务
  • 请告知我初始化hibernate会话功能的servlet上下文方法还可以,或者也可以有其他最佳方法。这是该项目的快照

    这是一段代码

    模型类

    package com.mkyong.customer.model;
    
    import java.util.Date;
    
    public class Customer implements java.io.Serializable {
    
        private Long customerId;
        private String name;
        private String address;
        private Date createdDate;
    
        //getter and setter methods
    }
    
    hbm映射文件

    <hibernate-mapping>
        <class name="com.mkyong.customer.model.Customer" 
        table="customer" catalog="mkyong">
    
            <id name="customerId" type="java.lang.Long">
                <column name="CUSTOMER_ID" />
                <generator class="identity" />
            </id>
            <property name="name" type="string">
                <column name="NAME" length="45" not-null="true" />
            </property>
            <property name="address" type="string">
                <column name="ADDRESS" not-null="true" />
            </property>
            <property name="createdDate" type="timestamp">
                <column name="CREATED_DATE" length="19" not-null="true" />
            </property>
        </class>
    </hibernate-mapping>
    
    最后是动作课

    ackage com.mkyong.customer.action;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.apache.struts2.ServletActionContext;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    
    import com.mkyong.customer.model.Customer;
    import com.mkyong.listener.HibernateListener;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    
    public class CustomerAction extends ActionSupport 
        implements ModelDriven{
    
        Customer customer = new Customer();
        List<Customer> customerList = new ArrayList<Customer>();
    
        public String execute() throws Exception {
            return SUCCESS;
        }
    
        public Object getModel() {
            return customer;
        }
    
        public List<Customer> getCustomerList() {
            return customerList;
        }
    
        public void setCustomerList(List<Customer> customerList) {
            this.customerList = customerList;
        }
    
        //save customer
        public String addCustomer() throws Exception{
    
            //get hibernate session from the servlet context
            SessionFactory sessionFactory = 
                 (SessionFactory) ServletActionContext.getServletContext()
                         .getAttribute(HibernateListener.KEY_NAME);
    
            Session session = sessionFactory.openSession();
    
            //save it
            customer.setCreatedDate(new Date());
    
            session.beginTransaction();
            session.save(customer);
            session.getTransaction().commit();
    
            //reload the customer list
            customerList = null;
            customerList = session.createQuery("from Customer").list();
    
            return SUCCESS;
    
        }
    
        //list all customers
        public String listCustomer() throws Exception{
    
            //get hibernate session from the servlet context
            SessionFactory sessionFactory = 
                 (SessionFactory) ServletActionContext.getServletContext()
                         .getAttribute(HibernateListener.KEY_NAME);
    
            Session session = sessionFactory.openSession();
    
            customerList = session.createQuery("from Customer").list();
    
            return SUCCESS;
    
        }   
    }
    
    ackage com.mkyong.customer.action;
    导入java.util.ArrayList;
    导入java.util.Date;
    导入java.util.List;
    导入org.apache.struts2.ServletActionContext;
    导入org.hibernate.Session;
    导入org.hibernate.SessionFactory;
    导入com.mkyong.customer.model.customer;
    导入com.mkyong.listener.HibernateListener;
    导入com.opensymphony.xwork2.ActionSupport;
    导入com.opensymphony.xwork2.ModelDriven;
    公共类CustomerAction扩展了ActionSupport
    实现模型驱动{
    客户=新客户();
    List customerList=new ArrayList();
    公共字符串execute()引发异常{
    回归成功;
    }
    公共对象getModel(){
    退货客户;
    }
    公共列表getCustomerList(){
    返回客户列表;
    }
    public void setCustomerList(列表customerList){
    this.customerList=customerList;
    }
    //拯救客户
    公共字符串addCustomer()引发异常{
    //从servlet上下文获取hibernate会话
    SessionFactory SessionFactory=
    (SessionFactory)ServletActionContext.getServletContext()
    .getAttribute(HibernateListener.KEY\u名称);
    Session Session=sessionFactory.openSession();
    //省省吧
    customer.setCreatedDate(新日期());
    session.beginTransaction();
    session.save(客户);
    session.getTransaction().commit();
    //重新加载客户列表
    customerList=null;
    customerList=session.createQuery(“来自客户”).list();
    回归成功;
    }
    //列出所有客户
    公共字符串listCustomer()引发异常{
    //从servlet上下文获取hibernate会话
    SessionFactory SessionFactory=
    (SessionFactory)ServletActionContext.getServletContext()
    .getAttribute(HibernateListener.KEY\u名称);
    Session Session=sessionFactory.openSession();
    customerList=session.createQuery(“来自客户”).list();
    回归成功;
    }   
    }
    

    伙计们,请发布更新后的代码,非常感谢,我在这方面感到骄傲

    我对阅读这个标题感到困惑,因为它提到了Spring和Hibernate,但读完之后,我发现它是Struts2和Hibernate。以下是我对您的输入的快速思考

    Struts2作为MVC框架用于web层,而Hibernate负责处理DB交互,尽管您始终可以使用这两种方法,并且可以在Struts2操作中注入Hibernate会话,但我不建议您使用这种方法。 我的建议是创建一个服务层,负责Struts2操作类和Hibernate层之间的交互,这将帮助您微调代码,并使您将来更容易进行任何代码更改或修改

    Struts2中已经有一个插件,允许您在action类中注入Hibernate会话

  • 但我仍然认为,不要将hibernate会话与Struts2操作混合使用,最好在两者之间放置一个服务层来实现这一点


    另外,由于您已经用Spring标记了您的问题,所以我相信您也在应用程序中使用Spring,因此最好让Spring处理您与Hibernate的交互,此外,引入服务层将有助于高效地进行事务划分,并尽可能地进行微调。

    您不想在
    ServletContext
    中放置Hibernate
    会话。会话不是线程安全的,Hibernate的最佳实践是为每个请求创建并销毁
    会话
    (或者
    EntityManager
    ,如果您使用JPA)


    这可以使用拦截器来完成。正如Umesh所指出的,您应该倾向于使用服务层类(如DAO)直接与会话交互,而不是从action类中使用它。这为您提供了模型层和控制器层之间更明确的分离。

    请仅发布代码和配置的相关部分。这太多了…完整的例子在url上,请仔细阅读并根据您的设计转换它,即添加服务层,以便我能够完全理解它,谢谢您使用Struts 2的servlet过滤器?如果是这样,过滤器是拦截器的替代品。最大的区别(AIUI)是拦截器将围绕操作包装会话,而过滤器将围绕整个请求包装会话,包括呈现阶段。如果您的模型只包含DTO,而不包含实体,那么您只需要操作中的会话,但是如果您希望您的模型包含实体,如果您想避免可怕的
    LazyInitializationException
    @Steven.,您将需要整个请求过程中的会话。完整的示例位于url mkyong.com/struts2/struts-2-hibernate-integration-example,请仔细阅读,并根据添加服务层的设计进行转换,以便我能理解它完全,Thanks@TomAnderson:拦截器会将其环绕在渲染器上
    package com.mkyong.listener;
    
    import java.net.URL;
    
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateListener implements ServletContextListener{
    
        private Configuration config;
        private SessionFactory factory;
        private String path = "/hibernate.cfg.xml";
        private static Class clazz = HibernateListener.class;
    
        public static final String KEY_NAME = clazz.getName();
    
        public void contextDestroyed(ServletContextEvent event) {
          //
        }
    
        public void contextInitialized(ServletContextEvent event) {
    
         try { 
                URL url = HibernateListener.class.getResource(path);
                config = new Configuration().configure(url);
                factory = config.buildSessionFactory();
    
                //save the Hibernate session factory into serlvet context
                event.getServletContext().setAttribute(KEY_NAME, factory);
          } catch (Exception e) {
                 System.out.println(e.getMessage());
           }
        }
    }
    
    ackage com.mkyong.customer.action;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import org.apache.struts2.ServletActionContext;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    
    import com.mkyong.customer.model.Customer;
    import com.mkyong.listener.HibernateListener;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    
    public class CustomerAction extends ActionSupport 
        implements ModelDriven{
    
        Customer customer = new Customer();
        List<Customer> customerList = new ArrayList<Customer>();
    
        public String execute() throws Exception {
            return SUCCESS;
        }
    
        public Object getModel() {
            return customer;
        }
    
        public List<Customer> getCustomerList() {
            return customerList;
        }
    
        public void setCustomerList(List<Customer> customerList) {
            this.customerList = customerList;
        }
    
        //save customer
        public String addCustomer() throws Exception{
    
            //get hibernate session from the servlet context
            SessionFactory sessionFactory = 
                 (SessionFactory) ServletActionContext.getServletContext()
                         .getAttribute(HibernateListener.KEY_NAME);
    
            Session session = sessionFactory.openSession();
    
            //save it
            customer.setCreatedDate(new Date());
    
            session.beginTransaction();
            session.save(customer);
            session.getTransaction().commit();
    
            //reload the customer list
            customerList = null;
            customerList = session.createQuery("from Customer").list();
    
            return SUCCESS;
    
        }
    
        //list all customers
        public String listCustomer() throws Exception{
    
            //get hibernate session from the servlet context
            SessionFactory sessionFactory = 
                 (SessionFactory) ServletActionContext.getServletContext()
                         .getAttribute(HibernateListener.KEY_NAME);
    
            Session session = sessionFactory.openSession();
    
            customerList = session.createQuery("from Customer").list();
    
            return SUCCESS;
    
        }   
    }