在hibernate + struts中使用sessionfactory的更好方法

时间:2014-06-23 09:55:16

标签: hibernate struts2

这是我的服务类,有一些方法正在执行CRUD操作,所以我的问题就像是一个总是打开单个方法的会话工厂并在方法执行后关闭它的好方法,还是有任何其他方式整个Web应用程序只提供一个会话工厂

 public class ContactService{
    public Contact add(Contact contact) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.save(contact);
        session.getTransaction().commit();
        return contact;
    }
    public Contact delete(Long id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Contact contact = (Contact) session.load(Contact.class, id);
        if(null != contact) {
            session.delete(contact);
        }
        session.getTransaction().commit();
        return contact;
    }

    public List<Contact> list() {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Contact> contacts = null;
        try {

            contacts = (List<Contact>)session.createQuery("from Contact").list();

        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        session.getTransaction().commit();
        return contacts;
    }
}

3 个答案:

答案 0 :(得分:0)

在包SessionFactoryManager.java内创建一个类名com.xyzapp.hibernate,如下所示

package com.xyzapp.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class SessionFactoryManager {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory(){

if(sessionFactory==null)
    //it search that hibernate.cfg.xml file is available in class path
    sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();

return sessionFactory;
}

}

每当你需要SessionFactory的对象时,请调用下面的

package com.xyzapp.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


import com.xyzapp.hibernate.SessionFactoryManager;      //import in ur class and create Session factory static object and use with whole method in a class same for all classes

public class ContactNoDAO {
private static SessionFactory sessionFactory=SessionFactoryManager.getSessionFactory();

public static String addContactNo(ContactNo contactno){
    Session session=sessionFactory.openSession();
    Transaction tr=null;
    String id=null;
    try{
        tr=session.beginTransaction();
        id=session.save(contactno).toString();
        tr.commit();
        session.close();
    }
    catch(HibernateException e){
        e.printStackTrace();
        if(tr!=null)tr.rollback();

    }
    return id;
}
}

尝试在ur class中调用sessionFactory一次;

答案 1 :(得分:0)

您需要有会话工厂可用于获取数据库访问操作的会话,如果您关闭sessionFactory,则连接池,兑现等将被清除。

因此,请保持会话工厂在应用程序生命周期内保持打开状态,并在关闭应用程序时关闭。

参见: http://docs.jboss.org/hibernate/orm/4.1/javadocs/org/hibernate/SessionFactory.html#close()

答案 2 :(得分:0)

我的建议Struts2 + Spring + Hibernate集成。

确保它,你有添加spring,hibernate,struts2依赖。

Step1:applicationContext.xml

    <?xml version="1.0" encoding="windows-1252"?>
 <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.5.xsd">

   <bean id="myDao" class="controller.DataBaseSessionFactory" scope="request" /> 
 </beans>

第2步:

包裹控制器;

 import model.HibernateUtil;
 import org.hibernate.Session;
 import org.hibernate.Transaction;
 import org.springframework.beans.factory.DisposableBean;
 import org.springframework.beans.factory.InitializingBean;

public class DataBaseSessionFactory implements InitializingBean, DisposableBean {

private Session dbsession;
private Transaction tx;

public Session getDbsession() {
    return dbsession;
}

@Override
public void afterPropertiesSet() throws Exception {
    try {
        dbsession = HibernateUtil.getSessionFactory().getCurrentSession();
        System.err.print("obtained current session");
    } catch (Exception e) {
        dbsession = HibernateUtil.getSessionFactory().openSession();
        System.err.print(e.getMessage() + "new session db created");
    }
    this.tx = dbsession.beginTransaction();
}

@Override
public void destroy() throws Exception {
    System.err.print("transaction commited");
    this.tx.commit();
}

public void rollback() throws Exception {
    System.err.print("transaction rollback");
    this.tx.rollback();
}
}

最后你可以在Actionclass中使用你的sessionfactory。

第3步:Action.class

private DataBaseSessionFactory myDao;

ex(){
  Contact c=(Contact) myDao.getDbsession().get(Contact.class, id);
  List<Contact> contacts = (List<Contact>)session.createQuery(Contact.class).list();
}