These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: Problem to refresh a list returned by IQuery
PostPosted: Wed Aug 22, 2007 10:34 am 
Newbie

Joined: Thu Jul 19, 2007 2:46 pm
Posts: 12
Hi everyone

I am having a problem whith NHIBERNATE

I am getting a list fom the database to populate a listbox in my system using the method bellow:

public IList<Processo> getProcessos()
{
IList<Processo> processos;
//Retorna todos os processos do banco de dados
processos = session.CreateQuery("from Processo").List<Processo>();


return processos;
}

The return value is a processo´s list

After the system save or update a 'processo' in the database to refresh the listbox whit the processo´s list, i call again the method getProcessos()

but i cant refresh the listbox, no matter how many times I insert a new processo or update the return of the method 'getProcessos()' is always the same, and i cant refresh my listbox

how i can solve this problem?

anyone can help me

sorry for the bad english, i need to practice more : )

thanks in advance


Hibernate version:
1.2 GA
Mapping documents:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- Add this element -->
<configSections>
<section
name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
/>
</configSections>

<!-- Add this element -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=MDDB04SP;initial catalog=DBSUM;User ID=usr_mddb04sp;Password=#jaera#;Min Pool Size=2</property>
<property name="ShowSql">true</property>

<mapping assembly="ProducaoMidiaMix" />

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


</configuration>

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="ProducaoMidiaMix.Negocio" assembly="ProducaoMidiaMix">


<class name="Processo" table="SPMM_PROCESSO">

<composite-id name="Processokey" class="ProducaoMidiaMix.Negocio.Processo+ProcessoKey, ProducaoMidiaMix" unsaved-value="none" access="property">
<key-property name="CodigoProcesso" type="System.Int32" column="PROCESSO_COD" />
<key-property name="DataInicial" type="System.DateTime" column="PROCESSO_DATAINICIO" />
</composite-id>

<property name="DataFinal" type="System.DateTime" column="PROCESSO_DATAFIM" not-null="true" />
<property name="NomeProcesso" type="System.String" column="PROCESSO_NOME" not-null="true" length="100" />
<property name="TipoProcesso" type="System.Int32" column="PROCESSO_FLAGTIPO" not-null="true" />
<property name="TipoPeriodo" type="System.Int32" column="PROCESSO_FLAGTIPOPERIODO" not-null="true" length="100" />
<property name="PeriodoInicial" type="System.Int32" column="PROCESSO_PERIODOINICIAL" not-null="true" />
<property name="PeriodoFinal" type="System.Int32" column="PROCESSO_PERIODOFINAL" not-null="true" />
<property name="FlagImportar" type="System.Boolean" column="PROCESSO_FLAGIMPORTAR" not-null="false" />
<property name="FlagPonderar" type="System.Boolean" column="PROCESSO_FLAGPONDERAR" not-null="false" />
<property name="FlagExportar" type="System.Boolean" column="PROCESSO_FLAGEXPORTAR" not-null="false" />
<property name="FlagFusao" type="System.Boolean" column="PROCESSO_FLAGFUSAO" not-null="false" />
<property name="TipoProcessoRadio" type="System.Int32" column="PROCESSO_TIPORADIO" not-null="false" />
<property name="Usuario" type="System.String" column="USUARIO_NOME" not-null="true" length="100" />


<bag name="ListaTarefa" inverse="true" lazy="true" cascade="none">
<key>
<column name="PROCESSO_COD" not-null="true" />
<column name="PROCESSO_DATAINICIO" not-null="true" />
</key>
<one-to-many class="ProducaoMidiaMix.Negocio.Tarefa, ProducaoMidiaMix" />
</bag>

<filter name="ProcessoAtual"
condition=":dataProcesso BETWEEN PROCESSO_DATAINICIO and PROCESSO_DATAFIM"/>

</class>

<filter-def name="ProcessoAtual">
<filter-param name="dataProcesso" type="date"/>
</filter-def>


</hibernate-mapping>

Code between sessionFactory.openSession() and session.close():
public static ISession getSession()
{
if (factory == null)
{
lock (typeof(NHibernateHelper))
{
XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));

log.Info("Log4Net Configurado e Inicializado");

configuration = new Configuration();

configuration.Configure("hibernate.cfg.xml");

factory = configuration.BuildSessionFactory();

log.Info("Hibernate Iniciado e configurado");

session = factory.OpenSession();
}
}

return session;
}

Full stack trace of any exception that occurs:

Name and version of the database you are using:
SQL SERVER 2000

The generated SQL (show_sql=true):
2007-08-22 10:52:57,782 [1] INFO NHibernate.Loader.Loader.GetResultSet(:0) NHibernate.Loader.Loader - select processo0_.PROCESSO_COD as PROCESSO1_0_, processo0_.PROCESSO_DATAINICIO as PROCESSO2_0_, processo0_.PROCESSO_DATAFIM as PROCESSO3_0_, processo0_.PROCESSO_NOME as PROCESSO4_0_, processo0_.PROCESSO_FLAGTIPO as PROCESSO5_0_, processo0_.PROCESSO_FLAGTIPOPERIODO as PROCESSO6_0_, processo0_.PROCESSO_PERIODOINICIAL as PROCESSO7_0_, processo0_.PROCESSO_PERIODOFINAL as PROCESSO8_0_, processo0_.PROCESSO_FLAGIMPORTAR as PROCESSO9_0_, processo0_.PROCESSO_FLAGPONDERAR as PROCESSO10_0_, processo0_.PROCESSO_FLAGEXPORTAR as PROCESSO11_0_, processo0_.PROCESSO_FLAGFUSAO as PROCESSO12_0_, processo0_.PROCESSO_TIPORADIO as PROCESSO13_0_, processo0_.USUARIO_NOME as USUARIO14_0_ from SPMM_PROCESSO processo0_ where @p0 BETWEEN processo0_.PROCESSO_DATAINICIO and processo0_.PROCESSO_DATAFIM


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 23, 2007 10:23 am 
Expert
Expert

Joined: Fri May 13, 2005 11:13 am
Posts: 292
Location: Rochester, NY
You didn't post any code relating to how you save or retrieve anything, but judging by the method you did post, it looks like you are using one Session for your whole application. My guess is that you aren't using transactions or flushing your session ever, so nothing ever gets saved to the database.

If I'm not correct, please post your other data access code so we can take a closer look at the problem.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 23, 2007 12:39 pm 
Newbie

Joined: Thu Jul 19, 2007 2:46 pm
Posts: 12
I using the same session for the entire application

here is how i create the session and get the session

public static ISession getSession()
{
if (factory == null)
{
lock (typeof(NHibernateHelper))
{
XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));

log.Info("Log4Net Configurado e Inicializado");

configuration = new Configuration();

configuration.Configure("hibernate.cfg.xml");

factory = configuration.BuildSessionFactory();

log.Info("Hibernate Iniciado e configurado");

session = factory.OpenSession();
}
}

return session;
}


Bellow it´s the code of the dao i am using

using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using ProducaoMidiaMix.Negocio;
using log4net;

namespace ProducaoMidiaMix.DAO
{
class ProcessoDao
{
public static readonly ILog log = LogManager.GetLogger(typeof(ProcessoDao));

ISession session;

IList<Processo> processos;

public ProcessoDao(ISession session)
{
this.session = session;

//Habilita o fitro pela data do processo mais atual
session.EnableFilter("ProcessoAtual").SetParameter("dataProcesso", DateTime.Now);
}

public IList<Processo> getProcessos()
{

//Retorna todos os processos do banco de dados
processos = session.CreateQuery("from Processo").List<Processo>();

return processos;
}




public void salvarProcesso(Processo processoNovo, Processo processoAtual)
{
ITransaction transaction = session.BeginTransaction();

Processo.ProcessoKey processoKey = new Processo.ProcessoKey();

processoNovo.Processokey = processoKey;

try
{
//Atribui a data atual para a chave do processo
processoNovo.Processokey.DataInicial = DateTime.Now;

//Atribui a data final para o processo novo
processoNovo.DataFinal = DateTime.MaxValue;

//Se existir algum processo selecionado atualizado o processo, senao salva um processo novo
if (processoAtual != null)
{
//Atribui o valor do codigo do processo para a chave
processoNovo.Processokey.CodigoProcesso = processoAtual.Processokey.CodigoProcesso;

//Salva a configuracao atual e cria o historico da ultima configuracao
processoAtual.DataFinal = DateTime.Now - TimeSpan.FromSeconds(1);

session.Update(processoAtual);

session.Save(processoNovo);
}
else
{
//Seleciona o maior valor de codigo de processo no banco e soma um para criar o codigo do processo a ser salvo
object maxCodigo = session.CreateQuery("select max(processo.Processokey.CodigoProcesso) from Processo as processo").UniqueResult();

if (maxCodigo == null)
{
processoNovo.Processokey.CodigoProcesso = 1;
}
else
{
processoNovo.Processokey.CodigoProcesso = (int)maxCodigo;
processoNovo.Processokey.CodigoProcesso++;
}

session.Save(processoNovo);
}



transaction.Commit();




}
catch (Exception exception)
{
transaction.Rollback();

log.Error(exception);

throw;
}

}

internal void excluirProcesso(Processo processo)
{

ITransaction transaction = session.BeginTransaction();

try
{
//Atribui a data atual para a chave do processo
processo.Processokey.DataInicial = DateTime.Now;

session.Save(processo);

transaction.Commit();
}
catch (Exception exception)
{
transaction.Rollback();

log.Error(exception);

throw;
}




}


}
}

after i save my object in the database by the hibernate, i cant make the method 'getProcessos' be refreshed, its always the same result

I discovered that if i disable the filter and enable again before i call the method 'getProcessos' the list returnd by the method is refreshed and solve my problem

I didnt understood what is happen but disable the filter resolve my problem

do you know why?

thanks in advance

sorry about all the comments in the code is in portuguese


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 24, 2007 12:04 am 
Expert
Expert

Joined: Fri May 13, 2005 11:13 am
Posts: 292
Location: Rochester, NY
I don't use filters and am not experienced with their internals, so I can't really help you there. I think the default mode for flushing provides that flushes occur at least on Commit()s, so I don't think the lack of Flush() calls in your code is the problem.

Unfortunately, all I can do is scold you about using the "singleton-session" anti-pattern. Sessions are just a step up from a unit-of-work, and are not robust enough to be carried through an entire app. They are inexpensive to create, fragile against exceptions, and not thread-safe. Moreover, they aren't meant to handle a large number of objects, which will make flushes sluggish.

I would seriously consider using a session-per-interaction or -conversation or -request pattern. There is lots of info on the web about NH usage patterns/practices.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.