-->
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.  [ 2 posts ] 
Author Message
 Post subject: Persist and load a tree structure
PostPosted: Thu Aug 21, 2008 4:29 pm 
Newbie

Joined: Thu Aug 21, 2008 4:03 pm
Posts: 2
Hibernate version: NHibernate 1.2.1.4000
Mapping documents: NHibernate.Mapping.Attributes ;-)
Name and version of the database you are using: SqlServerCe

Hallo ;-)

I want to persist and load a simple tree structure. The problem is not to get it work. The problem is that the loading of the complete tree lasts to much time ... because of lazy loading every item is loaded separately.
(Also when lazy is set to false)

I tried to "preload" all the items within a list. But the tree already uses lazy loading for every item ...

Does somebody know how to load the complete tree within only one SQL query?

I'm happy for every little hint ;-)

my simple test code:

(Program.cs)
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Mapping.Attributes;
using NHibernate.Dialect;
using NHibernate.Tool.hbm2ddl;
using System.Data;
using System.Data.SqlServerCe;

namespace NHibernateTreeTest
{
   [Class]
   public class Folder
   {
      public Folder()
      {
         this.SubFolders = new List<Folder>();
      }

      public Folder(string name)
      {
         this.Name = name;
         this.SubFolders = new List<Folder>();
      }

      [Id(0, Name = "Id"), Generator(1, Class = "identity")]
      public virtual int Id { get; set; }

      [Property]
      public virtual string Name { get; set; }

      [List(0)]
      [Key(1, Column = "ParentId")]
      [Index(2, Column = "ListIndex")]
      [OneToMany(3, ClassType = typeof(Folder))]
      public virtual IList<Folder> SubFolders { get; set; }
   }

   class Program
   {
      static void Main(string[] args)
      {
         Configuration cfg = createConfiguration();
         if (true)
            initializeDB(cfg);

         Console.Out.WriteLine("\nFolder structure:");

         ISessionFactory sessionFactory = cfg.BuildSessionFactory();
         ISession currentSession = sessionFactory.OpenSession();

         // makes it faster?! => no ;-)
         List<Folder> list = (List<Folder>)currentSession.CreateQuery("from Folder").List<Folder>();

         Folder root = (Folder)currentSession.Get(typeof(Folder), 1);
         if(root != null)
            writeFolder(root, 0);

         currentSession.Close();
         Console.ReadLine();
      }

      private static Configuration createConfiguration()
      {
         Configuration cfg = new Configuration();
         cfg.Configure();

         System.IO.MemoryStream ioStream = new System.IO.MemoryStream();
         HbmSerializer.Default.Serialize(ioStream, System.Reflection.Assembly.GetExecutingAssembly());

         ioStream.Position = 0;
         Console.Out.WriteLine(Encoding.ASCII.GetString(ioStream.GetBuffer()));
         cfg.AddInputStream(ioStream);
         ioStream.Close();

         return cfg;
      }

      private static void initializeDB(Configuration cfg)
      {
         SqlCeEngine engine = new SqlCeEngine("Data Source='DB.sdf';");
         if(System.IO.File.Exists("DB.sdf"))
            System.IO.File.Delete("DB.sdf");
         engine.CreateDatabase();

         ISessionFactory sessionFactory = cfg.BuildSessionFactory();
         ISession currentSession = sessionFactory.OpenSession();
         
         new SchemaExport(cfg).Execute(true, true, false, false);

         ITransaction transaction = currentSession.BeginTransaction();
         Folder root = new Folder("root");
         currentSession.Save(root);
         addRandomFolderTree(currentSession, root, 15);
         transaction.Commit();
      }

      private static Folder addRandomFolderTree(ISession currentSession, Folder folder, int level)
      {
         int childs = new Random().Next(level);
         for (int i = 0; i < childs; i++)
         {
            Folder newFolder = new Folder("folder " + level + "-" + i);
            currentSession.Save(newFolder);
            folder.SubFolders.Add(addRandomFolderTree(currentSession, newFolder, level - 1));
         }
         currentSession.SaveOrUpdate(folder);
         return folder;
      }

      private static void writeFolder(Folder folder, int level)
      {
         for (int i = 0; i < level; i++)
            Console.Out.Write("  ");
         Console.Out.WriteLine(folder.Name);
         for (int i = 0; i < folder.SubFolders.Count; i++)
            writeFolder(folder.SubFolders[i], level + 1);
      }
   }
}


(app.config)
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section
        name="hibernate-configuration"
        type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"
        />
   </configSections>
   <connectionStrings>
      <add name="NHibernateTest2.Properties.Settings.Database1ConnectionString"
        connectionString="Data Source=|DataDirectory|\Database1.sdf"
        providerName="Microsoft.SqlServerCe.Client.3.5" />
   </connectionStrings>
   <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <session-factory>
         <property name="show_sql">true</property>
         <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
         
         <property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
         <property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
         <property name="connection.connection_string">Data Source=DB.sdf</property>
         
         <property name="hibernate.max_fetch_depth">3</property>
         <mapping assembly="NHibernateTreeTest" />
      </session-factory>
   </hibernate-configuration>
</configuration>


Top
 Profile  
 
 Post subject:
PostPosted: Sat Aug 23, 2008 7:01 am 
Newbie

Joined: Fri Aug 22, 2008 5:57 pm
Posts: 3
Location: Russia, Moscow
Try to use attribute "batch-size" for your property SubFolders. This functionality is described in the article 15.1.5 "Using batch fetching" in the documentation. http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html_single/#performance-fetching-batch


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 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.