2009年9月4日金曜日

Monoで他のDBも使ってみたよ!+(db4o、NHibernate編)6


動作確認

基本的なDB操作(登録、更新、削除)を確認するために、以下のコード(C#)を使用します。使用するコードは「db4o編」の動作確認で使用したのと同様の構造で、操作上の違いはありません。

 作業する上でのディレクトリ構造は、下表の通りとします。

ディレクトリファイル
~/src/cs/NHibernateExampleIProductRepository.cs
~/src/cs/NHibernateExample/Testclient.cs
~/src/cs/NHibernateExample/TestDataProductRepository.cs, TestDataHelper.cs
IProductRepositoryインターフェース、ProductRepository、TestDataHelperクラス
[IProductRepository.cs]
  1. using System;  
  2.   
  3. namespace NHibernateExample  
  4. {  
  5.   public interface IProductRepository : IDisposable  
  6.   {  
  7.     void Add(Product product);  
  8.     void Update(Product product);  
  9.     void Remove(Product product);  
  10.     void GetAll();  
  11.   }  
  12. }  

[ProductRepository.cs]
 登録:ISession#Save、更新:ISession#Update、削除:ISession#Delete メソッドを使用します。
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using NHibernate;  
  5. using NHibernate.Cfg;  
  6. using NHibernate.Criterion;  
  7.   
  8. using NHibernateExample;  
  9.   
  10. namespace NHibernateExample.TestData  
  11. {  
  12.   public class ProductRepository : IProductRepository  
  13.   {  
  14.     private static IList<Product> _cache;  
  15.   
  16.     public void Add(Product product)  
  17.     {  
  18.       using (ISession session = TestDataHelper.OpenSession())  
  19.       using (ITransaction tran = session.BeginTransaction())  
  20.       {  
  21.         Product r1 = _getByIdFromCache(product.Id);  
  22.         if (r1 != null)  
  23.         {  
  24.           Console.WriteLine("Add:既にデータあり #1");  
  25.           return;  
  26.         }  
  27.   
  28.         Product r2 = _getById(session, product.Id);  
  29.         if (r2 != null)  
  30.         {  
  31.           Console.WriteLine("Add:既にデータあり #2");  
  32.           return;  
  33.         }  
  34.   
  35.         try  
  36.         {  
  37.           session.Save(product);  
  38.           tran.Commit();  
  39.         }  
  40.         catch(Exception ex)  
  41.         {  
  42.           Console.WriteLine("例外: {0}", ex.Message);  
  43.           tran.Rollback();  
  44.         }  
  45.       }  
  46.     }  
  47.   
  48.     public void Update(Product product)  
  49.     {  
  50.       using (ISession session = TestDataHelper.OpenSession())  
  51.       using (ITransaction tran = session.BeginTransaction())  
  52.       {  
  53.         Product r1 = _getByIdFromCache(product.Id);  
  54.         if (r1 == null)  
  55.         {  
  56.           Console.WriteLine("Update:該当データなし #1");  
  57.           return;  
  58.         }  
  59.   
  60.         Product r2 = _getByProduct(session, r1);  
  61.         if (r2 == null)  
  62.         {  
  63.           Console.WriteLine("Update:該当データなし #2");  
  64.           return;  
  65.         }  
  66.   
  67.         r2.Name        = product.Name;  
  68.         r2.Price       = product.Price;  
  69.         r2.Description = product.Description;  
  70.   
  71.         try  
  72.         {  
  73.           session.Update(r2);  
  74.           tran.Commit();  
  75.         }  
  76.         catch(Exception ex)  
  77.         {  
  78.           Console.WriteLine("例外: {0}", ex.Message);  
  79.           tran.Rollback();  
  80.         }  
  81.       }  
  82.     }  
  83.   
  84.     public void Remove(Product product)  
  85.     {  
  86.       using (ISession session = TestDataHelper.OpenSession())  
  87.       using (ITransaction tran = session.BeginTransaction())  
  88.       {  
  89.         Product r1 = _getByIdFromCache(product.Id);  
  90.         if (r1 == null)  
  91.         {  
  92.           Console.WriteLine("Remove:該当データなし #1");  
  93.           return;  
  94.         }  
  95.   
  96.         Product r2 = _getByProduct(session, r1);  
  97.         if (r2 == null)  
  98.         {  
  99.           Console.WriteLine("Remove:該当データなし #2");  
  100.           return;  
  101.         }  
  102.   
  103.         try  
  104.         {  
  105.           session.Delete(r2);  
  106.           tran.Commit();  
  107.         }  
  108.         catch(Exception ex)  
  109.         {  
  110.           Console.WriteLine("例外: {0}", ex.Message);  
  111.           tran.Rollback();  
  112.         }  
  113.       }  
  114.     }  
  115.   
  116.     public void GetAll()  
  117.     {  
  118.       using (ISession session = TestDataHelper.OpenSession())  
  119.       {  
  120.         _cache = session.CreateCriteria(typeof(Product))  
  121.           .AddOrder(Order.Asc("Id"))  
  122.           .List<Product>();  
  123.   
  124.         foreach (Product p in _cache)  
  125.         {  
  126.           Console.WriteLine(p);  
  127.         }  
  128.       }  
  129.     }  
  130.   
  131.     public void Dispose()  
  132.     {  
  133.     }  
  134.   
  135.     private Product _getById(ISession session, int id)  
  136.     {  
  137.       return session.Get<Product>(id);  
  138.     }  
  139.   
  140.     private Product _getByIdFromCache(int id)  
  141.     {  
  142.       return (from Product p in _cache    
  143.         where p.Id == id    
  144.         select p).SingleOrDefault();    
  145.     }  
  146.   
  147.     private Product _getByProduct(ISession session, Product product)  
  148.     {  
  149.       return session.CreateCriteria(typeof(Product))  
  150.         .Add(Expression.Eq("Id", product.Id))  
  151.         .Add(Expression.Eq("Name", product.Name))  
  152.         .Add(Expression.Eq("Price", product.Price))  
  153.         .Add(Expression.Eq("Description", product.Description))  
  154.         .UniqueResult<Product>();  
  155.     }  
  156.   }  
  157. }  

[TestDataHelper.cs]
  1. using System;  
  2. using NHibernate;  
  3. using NHibernate.Cfg;  
  4.   
  5. using NHibernateExample;  
  6.   
  7. namespace NHibernateExample.TestData  
  8. {  
  9.   public class TestDataHelper  
  10.   {  
  11.     private static ISessionFactory _factory;  
  12.   
  13.     private static ISessionFactory Factory  
  14.     {  
  15.       get  
  16.       {  
  17.         if (_factory == null)  
  18.         {  
  19.           string s;  
  20.           string cfg_prefix;  
  21.   
  22.           // 接続先DBMSの選択  
  23.           START:  
  24.           Console.Write("Connect to\n1:SQLite\n2:PostgreSQL\n3:MySQL\n4:SQLServer\n5:Oracle\n6:Firebird\n7:DB2\n?> ");  
  25.           s = Console.ReadLine();  
  26.           switch(s)  
  27.           {  
  28.             case "1": cfg_prefix = "SQLite";     break// SQLite  
  29.             case "2": cfg_prefix = "PostgreSQL"break// PostgreSQL  
  30.             case "3": cfg_prefix = "MySQL";      break// MySQL  
  31.             case "4": cfg_prefix = "SQLServer";  break// SQL Server  
  32.             case "5": cfg_prefix = "Oracle";     break// Oracle  
  33.             case "6": cfg_prefix = "Firebird";   break// Firebird  
  34.             case "7": cfg_prefix = "DB2";        break// DB2  
  35.             defaultgoto START;  
  36.           }  
  37.   
  38.           Configuration cfg = new Configuration();  
  39.           cfg.Configure(cfg_prefix + ".cfg.xml");  
  40.           _factory = cfg.BuildSessionFactory();  
  41.         }  
  42.         return _factory;  
  43.       }  
  44.     }  
  45.   
  46.     public static ISession OpenSession()  
  47.     {  
  48.       return Factory.OpenSession();  
  49.     }  
  50.   }  
  51. }  
ライブラリとしてビルドします。

[ビルド実行例]
$ cd ~/src/cs/NHibernateExample
$ gmcs -t:library -r:NHibernate.dll -out:./Test/NHibernateExample.dll Product.cs IProductRepository.cs -recurse:./Driver/*.cs -recurse:./TestData/*.cs
動作確認用プログラム
ProductRepositoryインスタンスを使用したDB操作を行います(「db4o編」で使用したのと同様のものです)。

[client.cs]
  1. using System;  
  2.   
  3. using NHibernateExample;  
  4. using NHibernateExample.TestData;  
  5.   
  6. namespace NHibernateExample.Test  
  7. {  
  8.   // 「db4o編」と同様  
  9. }  
  10. /* 
  11. * ビルド: 
  12. * 
  13. *   gmcs -r:NHibernateExample.dll client.cs 
  14. * 
  15. * 実行: 
  16. * 
  17. *   mono client.exe 
  18. * 
  19. */  

[実行例]
$ cd ~/src/cs/NHibernateExample/Test
$ mono client.exe
Connect to
1:SQLite
2:PostgreSQL
3:MySQL
4:SQLServer
5:Oracle
6:Firebird
7:DB2
?> 1
ID:0 NAME:SQLite 3 PRICE: DESCRIPTION:SQLite 3.6.10
ID:1 NAME:Clamp PRICE:12.48 DESCRIPTION:Workbench clamp
ID:50 NAME:Flat Head Screwdriver PRICE:3.17 DESCRIPTION:Flat head
ID:75 NAME:Tire Bar PRICE: DESCRIPTION:Tool for changing tires.
ID:3000 NAME:3mm Bracket PRICE:0.52 DESCRIPTION:

1:ADD
2:UPDATE
3:REMOVE
4:RELOAD
5:EXIT
?> 1
...

 Monoで他のDBも使ってみたよ!+(db4o、NHibernate編)7 へ続く。

0 件のコメント:

コメントを投稿