如何使Hibernate看到DB中的更改并与运行时对象实例同步

时间:2012-06-06 13:55:19

标签: hibernate session transactions struts

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

我正在开发一个带有hibernate 3(没有弹簧)的struts app 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;
        } 
    }

在TelevisionBL:

public Integer addTelevision(Usuario usuario,Integer idConocimiento,         boolean 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;
        }
    }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

,在finally块中,

session.close();

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

非常感谢Todd&amp;史蒂夫。