NHibernate Natalie Vegerina Software engineer Infostroy Ltd,

  • Размер: 2 Mегабайта
  • Количество слайдов: 52

Описание презентации NHibernate Natalie Vegerina Software engineer Infostroy Ltd, по слайдам

NHibernate Natalie Vegerina Software engineer Infostroy Ltd,  Kharkov, Ukraine NHibernate Natalie Vegerina Software engineer Infostroy Ltd, Kharkov, Ukraine

Схема базы данных Схема базы данных

Маппинг • Xml • Attributes • Conf. ORM • Fluent NHibernate • Auto mapping Маппинг • Xml • Attributes • Conf. ORM • Fluent NHibernate • Auto mapping

Xml- Маппинг Xml- Маппинг

Xml- маппинг ?  xml  version =  1. 0   encoding = Xml- маппинг

Xml- маппинг. Id  id  name =  Id   type =  IntXml- маппинг. Id

Xml- маппинг. Id  id  name =  Id   type =  IntXml- маппинг. Id

Xml- маппинг. Id Атрибуты:  • name • type • sql-type • column • length •Xml- маппинг. Id Атрибуты: • name • type • sql-type • column • length • not-null

Xml- маппинг. Id Генераторы:  • hilo • guid. comb • guid. native • uuid. hexXml- маппинг. Id Генераторы: • hilo • guid. comb • guid. native • uuid. hex • uuid. string • counter • increment • sequence • seqhilo • native • assigned • identity • foreign

Xml- маппинг. Property  property  name =  Name   not-null =  trueXml- маппинг. Property

Xml- маппинг. Property  property  name =  Name   type =  System.Xml- маппинг. Property

Схема базы данных Схема базы данных

Xml- маппинг. Many-to-one  class  name =  Line. Item     many-to-oneXml- маппинг. Many-to-one

Xml- маппинг. One-to-many  class  name =  Order    bag  nameXml- маппинг. One-to-many 0 » >

Xml- маппинг. One-to-many Cascade -типы:  • none • save-update • delete-orphan • all-delete-orphan Xml- маппинг. One-to-many Cascade -типы: • none • save-update • delete-orphan • all-delete-orphan

Xml- маппинг. One-to-many Типы коллекций Тип Описание set Элементы не отсортированы и уникальны bag Элементы неXml- маппинг. One-to-many Типы коллекций Тип Описание Элементы не отсортированы и уникальны Элементы не отсортированы и не уникальны Элементы отсортированы и не уникальны

Элементы отсортированы, состоят из ключа и значения Не рекомендуется использовать

Схема базы данных Схема базы данных

Xml- маппинг. Many-to-many  bag  name =  Products   table =  Line.Xml- маппинг. Many-to-many

Fluent- Маппинг Fluent- Маппинг

Fluent- маппинг public  class  Product. Map :  Class. Map  Product  {Fluent- маппинг public class Product. Map : Class. Map { public Product. Map() { // here we define the mapping details } }

Fluent- маппинг. Основные настройки Table( tbl_Product ); Schema( Ordering. System ); Not. Lazy. Load(); Fluent- маппинг. Основные настройки Table( «tbl_Product» ); Schema( «Ordering. System» ); Not. Lazy. Load();

Fluent- маппинг. Id Id(x = x. ID) . Generated. By. Hi. Lo( 1000 ); Fluent- маппинг. Id Id(x => x. ID) . Generated. By. Hi. Lo( «1000» );

Fluent- маппинг. Id Id(x = x. ID) . Column( PRODUCT_ID ) . Generated. By. Hi. Lo(Fluent- маппинг. Id Id(x => x. ID) . Column( «PRODUCT_ID» ) . Generated. By. Hi. Lo( «1000» ) . Unsaved. Value(-1);

Fluent- маппинг. Property Map(x = x. Name); Fluent- маппинг. Property Map(x => x. Name);

Fluent- маппинг. Property Map(x = x. Name,  PRODUCT_NAME ) . Length(50) . Not. Nullable(); Fluent- маппинг. Property Map(x => x. Name, «PRODUCT_NAME» ) . Length(50) . Not. Nullable();

Fluent- маппинг. Enum public  enum  Product. Types { Product. Type. A  /*. .Fluent- маппинг. Enum public enum Product. Types { Product. Type. A /*. . . */ } public class Product : Entity { public Product. Types Product. Type { get ; set ; } } Map(x => x. Product. Type) . Custom. Type();

Fluent- маппинг. Many-to-one References(x = x. Customer) . Not. Nullable() . Foreign. Key( Customer. Id )Fluent- маппинг. Many-to-one References(x => x. Customer) . Not. Nullable() . Foreign. Key( «Customer. Id» ) . Unique();

Fluent- маппинг. One-to-many Has. Many(x = x. Line. Items) . Inverse() . Cascade. All. Delete. Orphan()Fluent- маппинг. One-to-many Has. Many(x => x. Line. Items) . Inverse() . Cascade. All. Delete. Orphan() . Where(x => x. Discount > 0) . As. List();

Fluent- маппинг. Many-to-many public  class  Order :  Entity  Order  { publicFluent- маппинг. Many-to-many public class Order : Entity { public List Line. Items { get ; set ; } public List Products { get ; set ; } } Has. Many. To. Many(x => x. Products);

Auto mapping Auto mapping

Конвенция таблицы public  class  Table. Name. Convention :  IClass. Convention { public Конвенция таблицы public class Table. Name. Convention : IClass. Convention { public void Apply( IClass. Instance instance) { string type. Name = instance. Entity. Type. Name; instance. Table(type. Name. To. Upper() + «S» ); } }

Конвенция Id public  class  Id. Convention :  IId. Convention { public  voidКонвенция Id public class Id. Convention : IId. Convention { public void Apply( IIdentity. Instance instance) { instance. Column( «Id» ); instance. Generated. By. Sequence( string. Format( «Sequence_{0}» , instance. Entity. Type. Name)); instance. Unsaved. Value( «0» ); } }

Конвенция свойства public  class  Column. Convention :  IProperty. Convention { public  voidКонвенция свойства public class Column. Convention : IProperty. Convention { public void Apply( IProperty. Instance instance) { if (instance. Property. Name == «Name» ) { instance. Not. Nullable(); instance. Length(50); } } }

Конвенция свойства с атрибутом public  class  Max. Length. Convention :  Attribute. Property. ConventionКонвенция свойства с атрибутом public class Max. Length. Convention : Attribute. Property. Convention { protected override void Apply( Max. Length. Attribute attribute, IProperty. Instance instance) { instance. Length(attribute. Value); } }

Конвенция свойства с атрибутом public  class  Not. Required. Convention :  Attribute. Property. ConventionКонвенция свойства с атрибутом public class Not. Required. Convention : Attribute. Property. Convention { protected override void Apply( Not. Required. Attribute attribute, IProperty. Instance instance) { instance. Nullable(); } }

Конвенция внешнего ключа public  class  Custom. Foreign. Key. Convention :  Foreign. Key. ConventionКонвенция внешнего ключа public class Custom. Foreign. Key. Convention : Foreign. Key. Convention { protected override string Get. Key. Name( Member property, Type type) { if (property == null ) { return type. Name + «Id» ; // many-to-many, one-to-many, join } return property. Name + «Id» ; // many-to-one } }

Конвенция many-to-one public  class  Reference. Convention :  IReference. Convention { public  voidКонвенция many-to-one public class Reference. Convention : IReference. Convention { public void Apply( IMany. To. One. Instance instance) { instance. Cascade. None(); instance. Lazy. Load( Laziness. Proxy); instance. Column(instance. Property. Name + «Id» ); } }

Конвенция one-to-many public  class  One. To. Many. Convention :  IHas. Many. Convention {Конвенция one-to-many public class One. To. Many. Convention : IHas. Many. Convention { public void Apply( IOne. To. Many. Collection. Instance instance) { instance. Cascade. None(); instance. Inverse(); instance. Lazy. Load(); } }

NHibernate NHibernate

Обязательные настройки Название Пример значения Dialect NHibernate. Dialect. Ms. Sql 2008 Dialect Driver. Class NHibernate. Driver.Обязательные настройки Название Пример значения Dialect NHibernate. Dialect. Ms. Sql 2008 Dialect Driver. Class NHibernate. Driver. Sql. Client. Driver Connection. String Информация для соединения с базой данных Connection. Provider NHibernate. Connection. Driver. Connection. Provider Proxy. Factory NHibernate. Byte. Code. Castle. Proxy. Factory

Настройка NHibernate Типы настроек:  • config- файл • xml- файл • В коде • FluentНастройка NHibernate Типы настроек: • config- файл • xml- файл • В коде • Fluent • Conf. ORM

Настройка Nhibernate. Config- файл ? xml  version =  1. 0  ?  Настройка Nhibernate. Config- файл

NHibernate. Dialect. Oracle 10 g. Dialect NHibernate. Driver. Oracle. Data. Client. Driver NHibernate. Connection. Driver. Connection. Provider 10 NHibernate. Byte. Code. Castle. Proxy. Factory, NHibernate. Byte. Code. Castle true update

Настройка Nhibernate.  Фабрика сессий public  class  Db. Session. Factory :  IDisposable {Настройка Nhibernate. Фабрика сессий public class Db. Session. Factory : IDisposable { private static Db. Session. Factory instance; private ISession. Factory factory; static Db. Session. Factory() { instance = new Db. Session. Factory (); } public static Db. Session. Factory Instance { get { return instance; } }

Настройка Nhibernate.  Фабрика сессий public  ISession Open. Session() { return  this. factory. Open.Настройка Nhibernate. Фабрика сессий public ISession Open. Session() { return this. factory. Open. Session(); } public void Close() { if ( this. factory != null ) { this. factory. Close(); this. factory = null ; } } public void Dispose() { this. Close(); }

Настройка Nhibernate.  Фабрика сессий public  bool Create. Factory( string connection. String) { Configuration configurationНастройка Nhibernate. Фабрика сессий public bool Create. Factory( string connection. String) { Configuration configuration = Build. Configuration(connection. String); try { this. factory = configuration. Build. Session. Factory(); } catch ( Exception ex) { // manage exception } return this. factory != null ; }

Настройка Nhibernate.  Config- файл,  xml- маппинг private  static  Configuration Build. Configuration( stringНастройка Nhibernate. Config- файл, xml- маппинг private static Configuration Build. Configuration( string connection. String) { Configuration configuration = new Configuration (); configuration. Add. Assembly( Assembly. Get. Assembly( typeof ( Product ))); return configuration; }

Настройка Nhibernate. Код,  xml- маппинг private  static  Configuration Build. Configuration( string connection. String)Настройка Nhibernate. Код, xml- маппинг private static Configuration Build. Configuration( string connection. String) { Configuration configuration = new Configuration (); configuration. Data. Base. Integration(dbi => { dbi. Dialect(); dbi. Driver(); dbi. Connection. Provider(); dbi. Timeout = 15; }); configuration. Add. Assembly( Assembly. Get. Assembly( typeof ( Product ))); return configuration; }

Настройка Nhibernate.  Fluent private  static  Configuration Build. Configuration( string connection. String) { ConfigurationНастройка Nhibernate. Fluent private static Configuration Build. Configuration( string connection. String) { Configuration configuration = Fluently. Configure() . Database( Ms. Sql. Configuration. Ms. Sql 2008 . Connection. String(connection. String)) . Mappings(mappings => mappings. Fluent. Mappings . Add. From. Assembly. Of() . Build. Configuration(); return configuration; }

Настройка Nhibernate. Fluent , автоматический маппинг private  static  Configuration Build. Configuration( string connection. String)Настройка Nhibernate. Fluent , автоматический маппинг private static Configuration Build. Configuration( string connection. String) { Configuration configuration = new Configuration (); Auto. Persistence. Model model = new Auto. Persistence. Model (); model = Auto. Map. Assemblies( Assembly. Get. Assembly( typeof ( Product ))); model. Override. All(x => x. Ignore. Properties(y => y. Name. Starts. With( «Tmp_» ))); model. Ignore. Base(); model. Conventions. Add

(); model. Conventions. Add(); model. Conventions. Add(); model. Conventions. Add(); model. Conventions. Add(); model. Conventions. Add(); model. Configure(configuration); model. Write. Mappings. To( Path. Get. Temp. Path()); configuration. Set. Property( «connection_string» , connection. String); return configuration; }

Настройка Nhibernate. Web public  static  ISession Current. Db. Session { get {  Настройка Nhibernate. Web public static ISession Current. Db. Session { get { Http. Context context = Http. Context. Current; ISession session = ( ISession )context. Items[ «nhibernate. current_session» ]; if (session == null ) { session = Db. Session. Factory. Instance. Open. Session(); context. Items[ «nhibernate. current_session» ] = session; } return ( ISession )context. Items[ «nhibernate. current_session» ]; } }

Настройка Nhibernate. Web public  static  void Close. Current. Session() { Http. Context context =Настройка Nhibernate. Web public static void Close. Current. Session() { Http. Context context = Http. Context. Current; ISession session = (NHibernate. ISession )context. Items[ «nhibernate. current_session» ]; if (session != null ) { session. Close(); context. Items. Remove( «nhibernate. current_session» ); } }

Литература • Benjamin Perkins - Working with Nhibernate 3. 0 • Jason Dentler – Nhibernate 3.Литература • Benjamin Perkins — Working with Nhibernate 3. 0 • Jason Dentler – Nhibernate 3. 0. Cookbook • Dr. Gabriel Nicolas Schenker, Aaron Cure – Nhibernate 3. Beginners guide • Nhibernate — http: //www. nhforge. org/ • NHibernate — http: //ayende. com/blog • Fluent NHibernate — http: //wiki. fluentnhibernate. org/