-->
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.  [ 22 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Failed to lazily initialize a collection.session is disconec
PostPosted: Mon Oct 16, 2006 4:04 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp

Hibernate version: NHibernate v1.0.2

Mapping documents:
Department.hbm.xml
Code:
<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">

  <class name="DataTutorials.BLL.Department, DataTutorials.BLL"
  table="department">

    <id name="dept" column="DeptID" type="Int32" unsaved-value="0">
      <generator class="identity" />
    </id>
   
    <property name="name" column="deptname" type="String(50)"/>
   
    <bag name="classes" cascade="all" lazy="true">
      <key column="deptid"></key>
      <one-to-many class="DataTutorials.BLL.UniversityClass,DataTutorials.BLL"/>
    </bag>

    <bag name="professors" table="departmentprofessor" lazy="true">
      <key column="deptid"></key>
      <many-to-many class="DataTutorials.BLL.Person, DataTutorials.BLL"
                    column="PersonID" />
    </bag>
  </class>
</hibernate-mapping>


UniversityClasses.hbm.xml

Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">

  <class name="DataTutorials.BLL.UniversityClass, DataTutorials.BLL"
      table="universityclass">
   
    <id name="id" column="ClassID" type="Int32" unsaved-value="0">
      <generator class="identity" />
    </id>
   
    <property name="name" column="Classname" type="String(50)"/>
   
    <property name="number" column="ClassNumber" type="String(50)"/>
    <property name="syllabus" column="Syllabus" type="String(50)"/>
   
    <property name="startDate" column="StartDate" type="Date"/>
   
       
    <many-to-one name="Dept"
         class="DataTutorials.BLL.Department,DataTutorials.BLL"
            column="deptid"/>

    <many-to-one name="Prof"
         class="DataTutorials.BLL.Professor,DataTutorials.BLL"
            column="Personid"/>

    <bag name="students" table="StudentClass" lazy="true">
      <key column="ClassID"></key>
      <many-to-many class="DataTutorials.BLL.Person, DataTutorials.BLL"
                    column="PersonID" />
    </bag>
  </class>
</hibernate-mapping>



Code between sessionFactory.openSession() and session.close():

Code:
   

        static Configuration config;
        static ISessionFactory factory;
        static ISession session;

        static DBHandler()
        {
            config = new Configuration();
            config.AddClass(typeof(DataTutorials.BLL.Department));
            //config.AddClass(typeof(DataTutorials.BLL.Student));
            //config.AddClass(typeof(DataTutorials.BLL.Professor));
            config.AddClass(typeof(DataTutorials.BLL.Person));
            config.AddClass(typeof(DataTutorials.BLL.UniversityClass));

            try
            {
                factory = config.BuildSessionFactory();
                session = factory.OpenSession();
                session.Disconnect();
            }
            catch (Exception ex)
            {
                string errormsg = ex.Message;
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN THE CONSTRUCTOR ", ex, ex.Message);
            }
        }

    public IList GetDepartments()
        {
            session.Reconnect();
            ITransaction tx= session.BeginTransaction();
            IList retrievedDepts=null;
            try
            {
                retrievedDepts = session.CreateCriteria(typeof(DataTutorials.BLL.Department)).List();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                string errormsg = ex.Message;
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN getDepartments ", ex, ex.Message);
            }
            session.Disconnect();
            return retrievedDepts;
        }
        public Department GetDepartment(int deptID)
        {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();
            Department retrievedDept = null;
            try
            {
                retrievedDept = (Department)session.Load(typeof(DataTutorials.BLL.Department), deptID);
            }
            catch (Exception ex)
            {
                tx.Rollback();
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN Getting Department   ", ex, ex.Message);
            }
            session.Disconnect();
            return retrievedDept;
        }
        public void SaveDepartment(Department dept)
        {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();

            try
            {
                session.SaveOrUpdate(dept);
                tx.Commit();
            }
            catch(Exception ex)
            {
                tx.Rollback();
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN Save Department ", ex, ex.Message);
            }
            session.Disconnect();
        }
        public void DeleteDepartment(Department dept)
        {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();
            try
            {
                //session.deleteItem(Item);
                session.Delete(dept);
                tx.Commit();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                throw new ArgumentOutOfRangeException(ex.Message, ex, ex.Message);
            }
            session.Disconnect();
        }



Full stack trace of any exception that occurs:

[LazyInitializationException: Failed to lazily initialize a collection - session is disconnected]
NHibernate.Collection.PersistentCollection.Initialize(Boolean writing) +214
NHibernate.Collection.Bag.Add(Object value) +32
DataTutorials.DLLFacade.UniversityClassFacade.INSERT_UniversityClass(Int32 id, String name, String number, String syllabus, DateTime startdate, Int32 dept) in C:\Documents and Settings\bacem\Desktop\JAWAD ITECHKEY DAILY REPORTS\DataTutorials\Projects\DataTutorials -- Justin Gehtland\DataTutorials.DLLFacade\UniversityClassFacade.cs:72

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +72
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +358
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +486
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method) +38
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteInsert(IDictionary values) +731
System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback) +68
System.Web.UI.WebControls.DetailsView.HandleInsert(String commandArg, Boolean causesValidation) +392
System.Web.UI.WebControls.DetailsView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +609
System.Web.UI.WebControls.DetailsView.OnBubbleEvent(Object source, EventArgs e) +88
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
System.Web.UI.WebControls.DetailsViewRow.OnBubbleEvent(Object source, EventArgs e) +109
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +86
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +156
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4919




Name and version of the database you are using: SQLSERVER EXPRESS2005

The generated SQL (show_sql=true):

_________________
In Code We Trust


Top
 Profile  
 
 Post subject:
PostPosted: Mon Oct 16, 2006 5:31 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
I started to answer here, but then I realized You have asked no questions in the post. So, I brought the questions from another thread:

jojorico wrote:
i''m using a dbManager class which loads the configuration and i'm opening 1 session abd connecting and disconnecting to that session .

does that affect the nhibernate lazy loading ?


Appearantly it does. NHibernate can not access database if the session is disconnected. And It can not perform lazy loading if it can't access database, right?

jojorico wrote:
p.s:i'm using session.connect() and session.disconnect() in order to minimize the access to the database, is this true ?
or is the connection to the database opened in both cases ( if session is connected or not) ?


AFAIK, not - if You disconnect session, the the DB connection is closed. But about minimizing access to database - well, the database is accessed if some data is needed to read or save, so minimizing database access means minimizing data amount needed to read or save. And keep in mind that opening connection might be also quite costly - so in some cases it is better to keep connection open for a little bit longer than close/open it many times.

jojorico wrote:
how can i optimize .

Locate the code that performs badly and then try to improve it. There's no much point of optimizing if You do not know what is the bottleneck.

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject: How can i locate the problem ?
PostPosted: Mon Oct 16, 2006 8:58 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
10x for replying ...

if the Nhibernate lazy loading requires session connected than when should i close my connection or disconnect it ? on the page close or what ?

if so, i have a delete and insert functions which i'm using to add a Department and a UniversityClass object .. i'm testing my webpage by adding a UniversityClass than Deleting it ... sometimes it works sometimes it doesn't , it gives the message

Code:
No row with the given identifier exists: 118, of class: DataTutorials.BLL.UniversityClass
Parameter name: DBHandler - ERROR IN Getting Universitu Class   
Actual value was NHibernate.ObjectNotFoundException: No row with the given identifier exists: 118, of class: DataTutorials.BLL.UniversityClass
  at NHibernate.ObjectNotFoundException.ThrowIfNull(Object o, Object id, Type clazz)
  at NHibernate.Impl.SessionImpl.Load(Type clazz, Object id)
  at DataTutorials.DLL.DBHandler.GetUniversityClass(Int32 ClassID) in C:\Documents and Settings\bacem\Desktop\JAWAD ITECHKEY DAILY REPORTS\DataTutorials\Projects\DataTutorials -- Justin Gehtland\DataTutorials.DLL\DBHandler.cs:line 223.


i'm using transaction.commit() without using session.flush() Although i'm sure that the object is written to the db ... but i guess that sometimes the object is saved to the database sometimes not (although i can see the row added to the db all the times (during delete failure or success)... that's why delete succeeds a few times and fail a few other times ..


that's driving me mad :( :@

sometimes it works as charm, sometimes i get the previous message when deleting ... there is no logic in that !!!!
It tooooooooo hard for me to understand what's going on ...

Is there any way to understand what hibernate is doing behind the scenes ?

:( is there any demo application that contains a real implementation not like Justin Gehtland demo application which is quite simple but not useful in real applications ..

[/quote]

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Re: How can i locate the problem ?
PostPosted: Mon Oct 16, 2006 10:46 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
sometimes it works as charm, sometimes i get the previous message when deleting ... there is no logic in that !!!!
It tooooooooo hard for me to understand what's going on ...

Is there any way to understand what hibernate is doing behind the scenes ?


Belive, ther is a logic, It is just waiting You do figure it out :-P

As You do not post much details it is hard to guess what the problem is.
So, just a wild quess: If the session throws an exception, You may not use it any more.

Also, You exception handling code seems somewhat un-expected: If all goes well, You disconnect the session, byt if there is exception You leave it open.

Abd yes, in case of we application, disconnecting the session at the end of page request seems most appropriate.

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject: Reply
PostPosted: Tue Oct 17, 2006 3:42 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

In the preceding threads, u can find the mapping files implememtation and the code for handling nhibernate sessions and for deleting a Departmnet object ...
so almost all the needed information .

My insert method is 100% working but my delete method is sometimes raising errors (as if the row was not added in the database (although it is) and sometimes not :( :@
p.s:My nhibernate session isn't throwing an exception in both cases

an Example or sample application would explaing the idea if possible.

thanks in advance,
Jojo

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Re: Reply
PostPosted: Tue Oct 17, 2006 4:05 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
In the preceding threads, u can find the mapping files implememtation and the code for handling nhibernate sessions and for deleting a Departmnet object ...
so almost all the needed information .

My insert method is 100% working but my delete method is sometimes raising errors (as if the row was not added in the database (although it is) and sometimes not :( :@
p.s:My nhibernate session isn't throwing an exception in both cases

an Example or sample application would explaing the idea if possible.


Take a look into the exception stack You posted. It is not about error in delete - it is error in DBHandler.GetUniversityClass() So, are You sure that delete is giving an exception?

Another note - You are insconsistent in transaction handling. In some places You do BeginTransaction but no matching Commit(), only rollback... It might or might not raise some issues...

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject: Reply !!!!
PostPosted: Tue Oct 17, 2006 4:54 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

You are right .. it seems that m pb is residing in the Get University method, sometime it works sometimes not .. anyways, i've added the tx.commit() and i'm still having the arbitrary same old issue, here is an extract of my code:

Code:
   public IList GetUniversityClasses()

Code:
       {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();
            IList retrievedUniClasses = null;
            try
            {
                retrievedUniClasses = session.CreateCriteria(typeof(DataTutorials.BLL.UniversityClass)).List();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                string errormsg = ex.Message;
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN getUniversityClasses ", ex, ex.Message);
            }
            tx.Commit();
            session.Disconnect();
            return retrievedUniClasses;
        }
       
Code:
   public UniversityClass GetUniversityClass(int ClassID)

Code:
         {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();
            UniversityClass retrievedUniClass = null;
            try
            {
                retrievedUniClass = (UniversityClass)session.Load(typeof(DataTutorials.BLL.UniversityClass), ClassID);
            }
            catch (Exception ex)
            {
                tx.Rollback();
                throw new ArgumentOutOfRangeException("DBHandler - ERROR IN Getting Universitu Class   ", ex, ex.Message);
            }
            tx.Commit();
            session.Disconnect();
            return retrievedUniClass;
        }

   
Code:
   public void DeleteUniversityClass(UniversityClass UniClass)
Code:
           {
            session.Reconnect();
            ITransaction tx = session.BeginTransaction();
            try
            {
                //session.deleteItem(Item);
                session.Delete(UniClass);
                tx.Commit();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                throw new ArgumentOutOfRangeException(ex.Message, ex, ex.Message);
            }

            session.Disconnect();
        }

Code:
     public void INSERT_UniversityClass(int id, string name, string number, string syllabus, DateTime startdate,int dept)

Code:
          {
            UniversityClass UniClass = new UniversityClass(id, name, number, syllabus, startdate);

            Department Depart=dbManager.GetDepartment(dept);
            // Assigning that dept to our UniClass
            UniClass.Dept = Depart;

            dbManager.SaveUniversityClass(UniClass);

            // Hooray ! Fixture is successfully DONE

            // There is no need to save our UniversityClass --> It is already saved and assigned to the Department ..
            //dbManager.SaveUniversityClass(UniClass);
        }


[color=blue]Is there any ideas or suggestions ? :(

Thanks for ur time,
Jojo[/color]

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Re: Reply !!!!
PostPosted: Tue Oct 17, 2006 5:09 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
You are right .. it seems that m pb is residing in the Get University method, sometime it works sometimes not .. anyways, i've added the tx.commit() and i'm still having the arbitrary same old issue,



I would think that someone is quering for the object deleted just a moment before. Maybe some DataSource?

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject: Reply
PostPosted: Tue Oct 17, 2006 11:26 pm 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

Code:
        public object Get(Type type, object id)
        {
            object returnValue = null;

            try
            {
                returnValue = m_session.Load(type, id);

                return returnValue;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


This is the method i'm using to retrieve my objects from the database ...
sometimes it works sometimes it does not ( so the pb has not to do with the delete method as u've already said).

In fact, i've noticed that i'm facing this problem in all my application .. i thought that my pb resides in the session management !
so i've changed the architecture used in my session ( i used to configure it inside a Base Class constructor ..) to save my session inside the Http Context ... but i'm still getting the same error !

i can't figure what the problem is :( :(

Any other suggestions or ideas ?

do u have time to check my application ( i can send it via email )?


Thanks in advance
Regards,
Jojo

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Re: Reply
PostPosted: Wed Oct 18, 2006 2:54 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
Any other suggestions or ideas ?

do u have time to check my application ( i can send it via email )?



Have You actually tried to debug Your program? Like, set VS to break when exception is throw and insoect stack/variables and so on? I would strinlgy suggest that.

I'm not willing to search for error which "sometimes happens and sometimes does not happen". If You find a reliable way to reproduce the error and still not able to understand the cause (after using debugger), I may want to take a look into actual program.

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject: Thanks
PostPosted: Thu Oct 19, 2006 3:37 pm 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

Quote:
i really do appreciate your help and your time ...
in fact, i'm working on a sample application and it contains a few classes (3classes and 3 mapping files o course :p ) ..
Anyway, i'll review my code and provide you with further information .


Regards,
Jojo

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Error in Get and Delete Functions !
PostPosted: Fri Oct 20, 2006 6:38 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

First of all i'd like to make sure from the logic, plz correct me if that is wrong :

Quote:
when i use m_session.Load(Type,ObjID), the NHibernate creates an instance of the Class having the specified type, so there is no need to create an instance manually cause it will be handled as a new object (row)!!


i've set breakpoints on the GetDepartment(..) method and the DeleteDepartment(..) methods.

My DLL class (the Database manager class) :

Code:
    public class DBHandler
    {
        protected ISession m_session;

        public DBHandler()
        {
            m_session = NHibernateHttpModule.CurrentSession;
        }

        public object Get(Type type, object id)
        {
            object returnValue = null;
            ITransaction tx = null;

            try
            {
                tx = m_session.BeginTransaction();
                returnValue = m_session.Load(type, id);
                tx.Commit();

                return returnValue;
            }
            catch (Exception ex)
            {
                if (tx != null) tx.Rollback();
                string errormessage = ex.Message + " Exception in the DBhandler , Get(Type,object) method";
                throw new ArgumentOutOfRangeException(errormessage);
            }
        }

        public void Delete(object item)
        {
            ITransaction tx = null;

            try
            {
                tx = m_session.BeginTransaction();

                m_session.Delete(item);

                tx.Commit();
            }
            catch (Exception ex)
            {
                if (tx != null) tx.Rollback();
                string errormessage = ex.Message + " Exception in the DBhandler , Delete(object) method";
                throw new ArgumentOutOfRangeException(errormessage);
            }
        }

}


My Department Facade:

Code:
         public void INSERT_Department(int dept, string name)
        {
            Department Dept=new Department(dept,name);
            dbManager.SaveDepartment(Dept);
        }  dbManager.SaveDepartment(Dept);
        }
        public void DELETE_Department(int dept)
        {
            Department Dept = dbManager.GetDepartment(dept);
            dbManager.DeleteDepartment(Dept);
        }


In the presentation layer, i'm using an Object Data Source ..
That ODS calls the function INSERT_Department(...) when i click insert command button and DELETE_Department(...) when i click Delete command button.

i'm creating (inserting) an object and then deleting that object ..
The problem resides in deleting the object.

Here what i've got while debugging (while trying to delete a Department):

1-Sometimes i get no errors neither exceptions
the logic is correct:
Department Dept = dbManager.GetDepartment(dept) filled Dept with Departmennt object retrieved from the database .
and the dbManager.DeleteDepartment(Dept) successfully deleted the object.

2- Exception ... while trying to load the object from the database ... in the following line :
dbManager.GetDepartment(dept) ...
{
tx = m_session.BeginTransaction();
returnValue = m_session.Load(type, id);
return returnvalue;
}

Sometimes no exception is thrown but the order of execution changes ..
ex: while arriving to this line of code returnValue = m_session.Load(type, id); ; the compiler jumps to the delete function and execute it (The object is deleted ) than it returns the returnvalue .. When the object is returned , now the debugger will try execute the function dbManager.DeleteDepartment(Dept) (in the Department facade ); which is not possible cause the object is already deleted ! an EXception is thrown in the Delete funtion.
Sometimes the exception is thrown in the dbManager.GetDepartment(dept) method


But what i've noticed in general is that the problem resides in the
dbManager.GetDepartment(dept) ... {} method, more specifically in this line of code :
returnValue = m_session.Load(type, id);


so is that a session problem or an iis problem or a database problem or even an Nhibernate bug or pb, or am i forgetting something ??

i'm using ASP.net development server, and not the IIS does that affect my work (i'm declaring the SessionFactory and the session in a NHibernateHttpModule - i saved my session in the HTTP context ) ? how ?

i'm using : SqlServerExpress2005 with Asp.net v2.0 and NHibernate v1.0.2 ?

Regards,
Jojo

_________________
In Code We Trust


Top
 Profile  
 
 Post subject: Re: Error in Get and Delete Functions !
PostPosted: Fri Oct 20, 2006 7:03 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
Quote:
when i use m_session.Load(Type,ObjID), the NHibernate creates an instance of the Class having the specified type, so there is no need to create an instance manually cause it will be handled as a new object (row)!!


Yes. You might consider using session.Get() instead of session.Load(). The difference is that the session.Get() reads the values from database, but Load() just creates proxy instance if the type is lazy loaded.
jojorico wrote:
2- Exception ... while trying to load the object from the database ... in the following line :
dbManager.GetDepartment(dept) ...
{
tx = m_session.BeginTransaction();
returnValue = m_session.Load(type, id);
return returnvalue;
}

Sometimes no exception is thrown but the order of execution changes ..
ex: while arriving to this line of code returnValue = m_session.Load(type, id); ; the compiler jumps to the delete function and execute it (The object is deleted ) than it returns the returnvalue .. When the object is returned , now the debugger will try execute the function dbManager.DeleteDepartment(Dept) (in the Department facade ); which is not possible cause the object is already deleted ! an EXception is thrown in the Delete funtion.
Sometimes the exception is thrown in the dbManager.GetDepartment(dept) method


It sounds like the server is serving multiple Delete requests at the same time, in different threads. Try to identify ther request/thread that You are debugging when the context switch happens (the "Threads" window from debug meny) Inspecting session/request variables might also help (you may even store some own value in them to help identifing)

BTW, please use less formatting - it is hard to read :(

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
 Post subject:
PostPosted: Fri Oct 20, 2006 7:26 am 
Regular
Regular

Joined: Mon Aug 28, 2006 6:35 am
Posts: 66
Location: Middle East
Dear Gert,

sorry for the formatting, i thought that facilitate the reading :(

i'm getting error in the loading session.Load(Type,id); which results in changing the execution's order sometimes it throws an exception in the GetDepartment function, sometimes the compiler jumps to the deleteDepartment and throws an exception there, sometimes it jumps to the deleteDepartment and then get back to the GetDepartment function and throws an exception ...

what is common is that the Department dept=session.Load(Type,id); in the GetDepartment(type,id) (department facade class ) method changes the execution order :~ :|

so what may make the session.load() method fail, is it something related to the session management ?
by the way, in the Department class there are 2 collections (classes and professors ) which i'm not initializing (null)... do they affect the load ?

you've said something about the session.Get() method, is it related to the proxy ? cause i'm not declaring proxy element in my xml files !
so do i have to create an instance of the department class and initialize it using the session.Get() method ?

Regards,
Jojo

_________________
In Code We Trust


Top
 Profile  
 
 Post subject:
PostPosted: Fri Oct 20, 2006 10:39 am 
Expert
Expert

Joined: Thu Jan 19, 2006 4:29 pm
Posts: 348
jojorico wrote:
what is common is that the Department dept=session.Load(Type,id); in the GetDepartment(type,id) (department facade class ) method changes the execution order :~ :|


I strongly doubt that the execution order is changed. I strongly belive that You are watching two different threads executing concurrently.

I suggest You to write messages that identify the execution order to debug output of Visual Studio (see http://msdn2.microsoft.com/en-us/library/bs4c1wda.aspx for details, use some "Write" variant). Be sure to include Thread.CurrentThread.ManagedThreadId in output to be able to determine the execotion line.

jojorico wrote:
you've said something about the session.Get() method, is it related to the proxy ? cause i'm not declaring proxy element in my xml files !
so do i have to create an instance of the department class and initialize it using the session.Get() method?


lazy="true" for calsses is alternative for proxy element. Also, in NHibernate 1.2, lasy="true" is default (so, You must excplicitly write lazy="false" if You want avoid proxies)

So, in general, ISession.Get() and ISession.Load() are used in same manner. The difference is that Session.Get() loads data from database but Session.Load() will defer loading until the object data is actually used.

Gert

_________________
If a reply helps You, rate it!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 22 posts ]  Go to page 1, 2  Next

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.