FluentNHibernate + Lucene .Net

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

FluentNHibernate + Lucene .Net

文章rusli » 週二 4月 30, 2013 2:23 pm

NHibernate.Search Souce code:
https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk/src/NHibernate.Search

SimpleFluentNHibernateLucene.rar
(1.07 MiB) 已下載 36 次


packages.rar
(11.31 MiB) 已下載 32 次

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

FluentNHibernate - Entities

文章rusli » 週二 4月 30, 2013 3:32 pm

FluentNHibernate 好處:
1. 沒有 NHibernate 簡單但繁瑣的 hbm xml
2. 沒有 hbm xml 設定錯誤在 runtime 才知道錯誤問題
3, 沒有 bhm xml 重複工作設定反覆問題. 如: 設定每個屬性的 int 類型 default 為 -1


代碼: 選擇全部

    [Indexed]
    public class Employee
    {
        [DocumentId]
        public virtual int Id { get; protected set; }

        [Field(Index.Tokenized, Store = NHibernate.Search.Attributes.Store.Yes)]
        public virtual string FirstName { get; set; }

        [Field(Index.Tokenized, Store = NHibernate.Search.Attributes.Store.Yes)]
        public virtual string LastName { get; set; }

        [IndexedEmbedded(Depth = 1, Prefix = "Store_")]
        public virtual Store Store { get; set; }
    }
}


代碼: 選擇全部

    [Indexed]
    public class Product
    {
        [DocumentId]
        public virtual int Id { get; protected set; }
     
        [Field(Index.Tokenized, Store = NHibernate.Search.Attributes.Store.Yes)]
        public virtual string Name { get; set; }
       
        [Field(Index.Tokenized, Store = NHibernate.Search.Attributes.Store.Yes)]
        public virtual double Price { get; set; }
       
        [IndexedEmbedded(Depth = 1, Prefix = "StoresStockedIn_")]
        public virtual IList<Store> StoresStockedIn { get; protected set; }

        public Product()
        {
            StoresStockedIn = new List<Store>();
        }
    }


代碼: 選擇全部

 [Indexed]
    public class Store
    {
        [DocumentId]
        public virtual int Id { get; protected set; }

        [Field(Index.Tokenized, Store = NHibernate.Search.Attributes.Store.Yes)]
        public virtual string Name { get; set; }

        [IndexedEmbedded(Depth = 1, Prefix = "Products_")]
        public virtual IList<Product> Products { get; set; }

        [IndexedEmbedded(Depth = 1, Prefix = "Staff_")]
        public virtual IList<Employee> Staff { get; set; }

        public Store()
        {
            Products = new List<Product>();
            Staff = new List<Employee>();
        }

        public virtual void AddProduct(Product product)
        {
            product.StoresStockedIn.Add(this);
            Products.Add(product);
        }

        public virtual void AddEmployee(Employee emplyee)
        {
            emplyee.Store = this;
            Staff.Add(emplyee);
        }
    }

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

FluentNHibernate - Mapping

文章rusli » 週二 4月 30, 2013 3:33 pm

代碼: 選擇全部

    public class EmployeeMap : ClassMap<Employee>
    {
        public EmployeeMap()
        {
            Id(x => x.Id);
            Map(x => x.FirstName);
            Map(x => x.LastName);
            References(x => x.Store);
        }
    }


代碼: 選擇全部

    public class ProductMap : ClassMap<Product>
    {
        public ProductMap()
        {
            Id(x => x.Id);
            Map(x => x.Name);
            Map(x => x.Price);

            //// 多對多關係, Id 對到 relation table, "StoreProduct" 為該 TableName (NHibernate 自動建立)
            HasManyToMany(x => x.StoresStockedIn)
              .Cascade.All()
              .Inverse()
              .Table("StoreProduct");
        }
    }


代碼: 選擇全部

    public class EmployeeMap : ClassMap<Employee>
    {
        public EmployeeMap()
        {
            Id(x => x.Id);
            Map(x => x.FirstName);
            Map(x => x.LastName);
            References(x => x.Store);
        }
    }

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

FluentNHibernate - Extensions

文章rusli » 週二 4月 30, 2013 3:34 pm

代碼: 選擇全部

 public static class StoreExtension
    {
        public static void AddProductsToStore(this Store store, params Product[] products)
        {
            foreach (var product in products)
            {
                store.AddProduct(product);
            }
        }

        public static void AddEmployeesToStore(this Store store, params Employee[] employees)
        {
            foreach (var employee in employees)
            {
                store.AddEmployee(employee);
            }
        }
    }

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

FluentNHibernate - Helper

文章rusli » 週二 4月 30, 2013 3:34 pm

代碼: 選擇全部


    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();

                return _sessionFactory;
            }
        }

        private static void InitializeSessionFactory()
        {
            const string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.mdf;Integrated Security=True;";
            var config = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                              .ConnectionString(connection)
                              .ShowSql()
                )
                .Mappings(m =>
                          m.FluentMappings
                              .AddFromAssemblyOf<Store>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
                .BuildConfiguration();

            // ExposeConfiguration() Create database schema only if not existing
            // SchemaExport的create()方法第一個true表示顯示SQL語法至標準輸出,第二個true表示立即在資料庫中運行SQL語法

            // 支持 Lucene, 監聽 Update Insert Delete

            config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());

            var factory = config.BuildSessionFactory();
            _sessionFactory = factory;
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

主程式

文章rusli » 週二 4月 30, 2013 3:35 pm

代碼: 選擇全部

    public class HomeModel
    {
        public HomeModel()
        {
            // Create
            Create("遠東百貨");
            Create("超級市場");

            Store store1 = Read("遠東百貨");

            // Update
            store1.Name = "遠東百貨1";
            Update(store1);


            // Read
            Store store2 = Read("遠東百貨"); // return null
            Store store3 = Read("遠東百貨1");

            // Delete
            Delete(store3);
        }

        private void Delete(Store store)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Delete(store);
                    transaction.Commit();
                }
            }
        }

        private void Update(Store store)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(store);
                    transaction.Commit();
                }
            }
        }

        private Store Read(string storeName)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                var makeQuery = (from store in session.Query<Store>()
                                 where store.Name == storeName
                                 select store).FirstOrDefault();
                return makeQuery;
            }
        }

        private void Create(string storeName)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var barginBasin = new Store { Name = storeName };

                    var potatoes = new Product { Name = storeName + "_Potatoes", Price = 3.60 };
                    var fish = new Product { Name = storeName + "_Fish", Price = 4.49 };
                    var milk = new Product { Name = storeName + "_Milk", Price = 0.79 };
                    var bread = new Product { Name = storeName + "_Bread", Price = 1.29 };
                    var cheese = new Product { Name = storeName + "_Cheese", Price = 2.10 };
                    var waffles = new Product { Name = storeName + "_Waffles", Price = 2.41 };

                    var daisy = new Employee { FirstName = storeName + "_Daisy", LastName = "Harrison" };
                    var jack = new Employee { FirstName = storeName + "_Jack", LastName = "Torrance" };
                    var sue = new Employee { FirstName = storeName + "_Sue", LastName = "Walkters" };
                    var bill = new Employee { FirstName = storeName + "_Bill", LastName = "Taft" };
                    var joan = new Employee { FirstName = storeName + "_Joan", LastName = "Pope" };

                    // 建立關聯
                    barginBasin.AddProductsToStore(potatoes, fish, milk, bread, cheese, waffles);
                    barginBasin.AddEmployeesToStore(daisy, jack, sue, bill, joan);

                    // 存檔
                    session.SaveOrUpdate(barginBasin);
                    transaction.Commit();
                }
            }
        }
    }

rusli
Site Admin
文章: 212
註冊時間: 週三 7月 07, 2010 9:49 pm

Re: FluentNHibernate + Lucene .Net

文章rusli » 週二 4月 30, 2013 3:36 pm

代碼: 選擇全部

<configuration>
  <configSections>
    <section name="hibernate-configuratin" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" requirePermission="false" />
    <section name="nhs-configuration" type="NHibernate.Search.Cfg.ConfigurationSectionHandler, NHibernate.Search" requirePermission="false" />
  </configSections>
  <nhs-configuration xmlns="urn:nhs-configuration-1.0">
    <search-factory>
      <property name="hibernate.search.default.directory_provier">NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
      <property name="hibernate.search.default.indexBase">~\App_Data\LuceneIndex</property>
      <property name="hibernate.search.indexing_strategy">event</property>
    </search-factory>
  </nhs-configuration>
  <appSettings>
    <add key="Lucene.Net.lockdir" value="~\App_Data\LuceneIndex" />
    ... 略 ...
</configuration>


回到「Lucene .Net」

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 1 位訪客