0

首先澄清一下,我在发布之前检查了很多帖子。也许我只是无法理解,但解决方案已发布。

我正在开发一个带有休眠 3(无弹簧)的 struts 应用程序 v 1.2.9。我的问题是,例如,如果我删除了一个实体,我确实提交了,那么我可以看到数据库中的更改是好的。但是,如果我查询表,请检索我提前删除的这个实体。

这是我的 hibernate.cfg.xml 的一部分

<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">XXXXXXXXXXXXXXX</property>
<property name="hibernate.connection.username">X</property>
<property name="hibernate.connection.password">X</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">validate</property>

org.hibernate.cache.NoCacheProvider

我的 HibernateUtil(从其他帖子复制)

 import org.hibernate.SessionFactory;

      import org.hibernate.cfg.Configuration;

      public class HibernateUtil {

            private static final SessionFactory sessionFactory;

            static {
                try {
                    // Create the SessionFactory from hibernate.cfg.xml
                sessionFactory = new           Configuration().configure().buildSessionFactory();

                } catch (Throwable ex) {
                    // Make sure you log the exception, as it might be swallowed
                    System.err.println("Initial SessionFactory creation failed." + ex);
                    throw new ExceptionInInitializerError(ex);
                }
            }

            public static SessionFactory getSessionFactory() {
                return sessionFactory;
            }

还有我的 DAO

import com.mylib.modelo.Television;
import com.mylib.plugins.HibernateUtil;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mylib.plugins.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;


public class TelevisionsDAO  {

   private static final Log log = LogFactory.getLog(TelevisionsDAO.class);

    public Television getTelevisionById(int idTelevision){
        Session session=null;
        Transaction tx =null;
        Television rs =null;
        try{
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            session.flush();

            //QJ: Use Hibernate Criteria for more secured functionalities
            rs=(Television) session.createCriteria(Television.class)
                     .add(Restrictions.eq("idTelevision", idTelevision))
                     .uniqueResult();
            if(rs!=null)session.refresh(rs);
            tx.commit();
        }catch(HibernateException e){
            e.printStackTrace();
        }
         return rs;
    }
    public List<Television> encuentraTelevisions(Integer idUsuario){
        Session session=null;
        Transaction tx =null;
        List rs =null;
        try{
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            //QJ: Use Hibernate Criteria for more secured functionalities
            rs=(List)session.createCriteria(Television.class)
                     .add(Restrictions.eq("usuario.idUsuario", idUsuario))
                     .list();
        }catch(HibernateException e){
            e.printStackTrace();
        }
         return rs;
    }

    public List<Television> encuentraTelevisions(Integer idUsuario, Boolean buscaOfrece){
        Session session=null;
        Transaction tx =null;
        List rs =null;
        try{
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            //QJ: Use Hibernate Criteria for more secured functionalities
            rs=(List)session.createCriteria(Television.class)
                     .add(Restrictions.eq("usuario.idUsuario", idUsuario))
                     .add(Restrictions.eq("buscaOfrece", buscaOfrece))
                     .list();
//            for(int i=0;i<rs.size();i++){
//                session.refresh((Television)rs.get(i));
//            }
            tx.commit();
        }catch(HibernateException e){
            e.printStackTrace();
        }
         return rs;
    }

    public boolean hasTelevision(Integer idUsuario, Boolean buscaOfrece,
            Integer idConocimiento){
        Session session=null;
        Transaction tx =null;
        List rs =null;
        try{
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            //session.flush();
            //QJ: Use Hibernate Criteria for more secured functionalities
            rs=(List)session.createCriteria(Television.class)
                     .add(Restrictions.eq("usuario.idUsuario", idUsuario))
                     .add(Restrictions.eq("buscaOfrece", buscaOfrece))
                     .add(Restrictions.eq("conocimiento.idConocimiento", idConocimiento))
                     .list();
            tx.commit();
        }catch(HibernateException e){
            e.printStackTrace();
        }
         return rs.size()>0;
    }

    public Integer addTelevision(Television television) throws Exception {
        log.info("addTelevision");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        try {
            Integer p = (Integer) session.save(television);
            session.flush();
            session.refresh(television);
            tx.commit();

            log.info("end addTelevision");
            return p;
        } catch (HibernateException e) {
            log.error("addTelevision", e);
            tx.rollback();
            throw e;
        }
    }

    public void quitarTelevision(Television television) throws Exception {
        log.info("quitarTelevision");

        Session session= HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        try {
            session.delete(television);
            session.flush();
            //session.refresh(television);
            tx.commit();

        } catch (HibernateException e) {
            log.error("quitarTelevision", e);
            tx.rollback();
            throw e;
        } 
    }

在 TVBL 中:

公共整数addTelevision(Usuario usuario,整数idConocimiento,布尔buscaOfrece)抛出异常{

    //compruebo que el usuario no contiene la telerencia en cuestión       
    if(!televisionDAO.hasTelevision(
            usuario.getIdUsuario(), buscaOfrece, idConocimiento)){
        Television tel = new Television();
        tel.setBuscaOfrece(buscaOfrece);
        tel.setUsuario(usuario);
        tel.setConocimiento(new Conocimiento(idConocimiento));
        return telerenciasDAO.addTelevision(tel);
    }else{
        return -1;
    }
  }

   public boolean quitarTelevisionSafe(Integer idTelevision, Integer idUsuarioRequesting) throws Exception{
        Television television = televisionsDAO.getTelevisionById(idTelevision.intValue());
        if( television.getUsuario().getIdUsuario().intValue() == idUsuarioRequesting.intValue() ){
            televisionsDAO.quitarTelevision(television);
            return true;
        }else{
            return false;
        }
    }
4

2 回答 2

0

在某些时候,您需要关闭会话。

于 2012-06-06T14:01:11.187 回答
0

考虑到我现在真的不知道会话是否打开(使用 getCurrentSession())以及何时关闭,因为会话关闭不起作用,尽管我在一些文章中读到了建议每次会话都没有打开,我决定控制它,我改变了我所有的 DAO 方法,每次都打开和关闭会话

Session session= HibernateUtil.getSessionFactory().openSession();

并且,在 finally 块中,

session.close();

我想做一个更有效的代码,但如果这样有效,我可以忍受它。下一次,我会将 Spring MVC 集成到我的应用程序中,以帮助控制事务性。

非常感谢托德和史蒂夫。

于 2012-06-07T09:27:09.117 回答