集成Struts 2和hibernate的最佳方法

时间:2012-07-24 16:41:26

标签: java spring hibernate struts2

我打算整合hibernate和struts2。请告知哪个是最好的方法,我想在Struts2中,没有正式的插件来集成Hibernate框架。但是,您可以通过以下步骤解决问题:

  1. 注册自定义ServletContextListener。
  2. 在ServletContextListener类中,初始化Hibernate会话并将其存储到servlet上下文中。
  3. 在action类中,从servlet上下文中获取Hibernate会话,并正常执行Hibernate任务。
  4. 请告知我的用于初始化hibernate会话部分的servlet上下文的方法是正确的,或者也可以有其他最好的approch。这是该项目的快照。

    这是一段代码..

    模特班......

    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>
    

    配置文件是......

    <hibernate-configuration>
      <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="use_sql_comments">false</property>
        <mapping resource="com/mkyong/customer/hibernate/Customer.hbm.xml" />
      </session-factory>
    </hibernate-configuration>
    

    听众班......

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

    伙计们请发布更新的代码非常感谢,我对此感到困惑.. !!

3 个答案:

答案 0 :(得分:1)

我对阅读标题感到困惑,因为它提到了Spring和Hibernate,但在阅读之后,它出现了Struts2和Hibernate。这是我对你的输入的快速想法

Struts2用于Web层作为MVC框架,而Hibernate负责处理数据库交互,虽然你总是可以使用两者并且可以在Struts2动作中注入hibernate会话,但我不会建议你采用这种方法。 我的建议是创建一个服务层,它应该负责你的Struts2动作类和你的Hibernate层之间的交互,这将帮助你微调你的代码,并使你更容易进行任何代码更改或任何修改将来

Struts2中已经有一个插件允许你在动作类中注入Hibernate会话

  1. full-hibernate-plugin-for-struts2/
  2. 但我仍然认为不要将hibernate会话与Struts2动作混合在一起,最好在两者之间放置一个Service层来执行此操作。

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

答案 1 :(得分:1)

您不想在Session中放置一个Hibernate ServletContext。会话不是线程安全的,Hibernate的最佳做法是为每个请求创建和销毁Session(如果使用JPA,则为EntityManager

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

答案 2 :(得分:0)

我找到了这个链接 Hibernate and Struts 2 Integration。这是进行整合的正确方法吗?