[hibernate] Problema no update

3 respostas
Aislim_Shanon

Após fazer uma alteração, apesar de no banco os dados ficarem corretos, nem sempre eles aparecem nas consultas corretamente… Dando refersh na página, a exibição altera entre a nova e a antiga versão do objeto.

Meu DAO:

@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class BaseRepositoryHibernate<T extends Identifiable> implements BaseRepository<T> {

	
	
	protected BaseRepositoryHibernate() {
		
	}
	

	@Qualifier("sessionFactory")
	public static final SessionFactory sessionFactory;
	
    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure("./hibernate.cfg.xml").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 final ThreadLocal session = new ThreadLocal();
    
    public static Session getSession() throws HibernateException {
        Session s = (Session) session.get();
        
        // Open a new Session, if this thread has none yet
        
        if (s == null || !s.isOpen()) {
            s = getSessionFactory().openSession();
            s.setFlushMode(FlushMode.MANUAL);
            
            if (s.getTransaction() == null){
            	s.beginTransaction();
            }
            else if(!s.getTransaction().isActive()){
            	s.getTransaction().begin();
            }
         // Store it in the ThreadLocal variable
            session.set(s);
        }
            
        // flush da sessao ocorre a cada query 
        s.flush();
       
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s != null)
        	
//            s.close();
        	getSessionFactory().close();
            session.set(null);
    }
    
    /**
     * @return the hibernate session factory
     */
    public static SessionFactory getSessionFactory() {
      return sessionFactory;
    }

    /**
     * This is a simple method to reduce the amount of code that needs
     * to be written every time hibernate is used.
     */
    public static void rollback(org.hibernate.Transaction tx) {
        if (tx != null) {
            try {
                tx.rollback();
            }
            catch (HibernateException ex) {
                // Probably don't need to do anything - this is likely being
                // called because of another exception, and we don't want to
                // mask it with yet another exception.
            }
        }
    }
    /**
     * This is a simple method to reduce the amount of code that needs
     * to be written every time hibernate is used.
     */
    public static void commit(org.hibernate.Transaction tx) {
        if (tx != null) {
            try {
                tx.commit();
                getSession().flush();
            }
            catch (HibernateException ex) {
                // Probably don't need to do anything - this is likely being
                // called because of another exception, and we don't want to
                // mask it with yet another exception.
            	if (tx != null) tx.rollback();
            	
            	getSession().clear();
            	
        	    throw ex; // or display error message
        	}
        	finally {
        		
        	    closeSession();
            }
        }
    }



	public void update(T obj) {
        
            	getSession().update(obj);
        		commit(getSession().getTransaction());
           
        
	}
	
	public T get(Long id) {
		return (T) getSession().get(getType(), id);
	}

E meu arquivo de configuração:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<property name="connection.url">jdbc:mysql://localhost:3306/pap?autoReconnect=true</property>
	<property name="connection.username">root</property>
	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
	<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
	<property name="connection.password">senha</property>
	<property name="hibernate.connection.charSet">ISO8859_1</property> 
 	<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    
    <!-- this will show us all sql statements -->
    <property name="hibernate.show_sql">true</property>
    
	<property name="hibernate.format_sql">true</property>
	<property name="hibernate.generate_statistics">false</property>
	<property name="hibernate.dbcp.maxActive">180</property>
	<property name="hibernate.dbcp.whenExhaustedAction">2</property>
	<property name="hibernate.dbcp.maxWait">12000</property>
	<property name="hibernate.dbcp.maxIdle">10</property>
	<property name="hibernate.connection.release_mode">on_close</property>

	<!-- mapping files -->
	<mapping resource="mappings/Assunto.hbm.xml" />
	<mapping resource="mappings/Grupo.hbm.xml" />
	<mapping resource="mappings/Instituicao.hbm.xml" />
	<mapping resource="mappings/Lista.hbm.xml" />
	<mapping resource="mappings/Problema.hbm.xml" />
	<mapping resource="mappings/Resolucao.hbm.xml" />
	<mapping resource="mappings/Usuario.hbm.xml" />
	<mapping resource="mappings/Arquivo.hbm.xml" />
	<mapping resource="mappings/Tarefa.hbm.xml" />

</session-factory>
</hibernate-configuration>

Se alguém puder dar alguma idéia…

Obrigada =]

3 Respostas

zorba

se no banco ta certo, e após um refresh, os dados mudam, parece ser algo com cache, não com hibernate

Aislim_Shanon

Se ficar dando refresh repetidas vezes, os dados ficam alternando…

zorba

bah! nunca vi coisa parecida…mas acho que logo vem algum ninja aqui e te responde :stuck_out_tongue:

Criado 3 de novembro de 2010
Ultima resposta 4 de nov. de 2010
Respostas 3
Participantes 2