My_NHibernate.ppt
- Количество слайдов: 52
NHibernate Natalie Vegerina Software engineer Infostroy Ltd, Kharkov, Ukraine
Схема базы данных
Маппинг • • • Xml Attributes Conf. ORM Fluent NHibernate Auto mapping
Xml-Маппинг
Xml-маппинг <? xml version="1. 0" encoding="utf-8" ? > <hibernate-mapping xmlns="urn: nhibernate-mapping-2. 2" assembly="Ordering. System" namespace="Ordering. System. Domain"> <class name="Product"> <id name="Id"> <generator class="native"/> </id> <property name="Name" not-null="true" length="50"/> <property name="Unit. Price" not-null="true" /> <property name="Reorder. Level" not-null="true" /> <property name="Discontinued" not-null="true" /> </class> </hibernate-mapping>
Xml-маппинг. Id <id name="Id" type="Int 32" unsaved-value="null"> <generator class="hilo"/> </id>
Xml-маппинг. Id <id name="Id" type="Int 32" unsaved-value="null"> <column name="product_id"/> <generator class="hilo"/> </id>
Xml-маппинг. Id Атрибуты: • name • type • sql-type • column • length • not-null
Xml-маппинг. 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="true" length="50"/>
Xml-маппинг. Property <property name="Name" type="System. String" not-null="true" length="50"> <column name="product_name" sql-type="char(50)" not-null="true"/> </property>
Схема базы данных
Xml-маппинг. Many-to-one <class name="Line. Item"> <many-to-one name="Order" class="Order" column="Order. Id" not-null="true"/> </class>
Xml-маппинг. One-to-many <class name="Order"> <bag name="Line. Items" lazy="true" inverse="true" cascade="all-delete-orphan" where="Discount > 0"> <key column="Order. Id"/> <one-to-many class="Line. Item"/> </bag> </class>
Xml-маппинг. One-to-many Cascade-типы: • • • none save-update delete-orphan all-delete-orphan
Xml-маппинг. One-to-many Типы коллекций Тип Описание <set> Элементы не отсортированы и уникальны <bag> Элементы не отсортированы и не уникальны <list> Элементы отсортированы и не уникальны <map> Элементы отсортированы, состоят из ключа и значения <idbag> Не рекомендуется использовать
Схема базы данных
Xml-маппинг. Many-to-many <bag name="Products" table="Line. Items"> <key column="Order. Id"/> <many-to-many class="Product" column="Product. Id" /> </bag>
Fluent-Маппинг
Fluent-маппинг public class Product. Map : Class. Map<Product> { public Product. Map() { // here we define the mapping details } }
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) . Column("PRODUCT_ID") . Generated. By. Hi. Lo("1000") . Unsaved. Value(-1);
Fluent-маппинг. Property Map(x => x. Name);
Fluent-маппинг. Property Map(x => x. Name, "PRODUCT_NAME") . Length(50) . Not. Nullable();
Fluent-маппинг. Enum public enum Product. Types { Product. Type. A /*. . . */ } public class Product : Entity<Product> { public Product. Types Product. Type { get; set; } } Map(x => x. Product. Type) . Custom. Type<Product. Types>();
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() . Where(x => x. Discount > 0) . As. List();
Fluent-маппинг. Many-to-many public class Order : Entity<Order> { public List<Line. Item> Line. Items { get; set; } public List<Product> Products { get; set; } } Has. Many. To. Many(x => x. Products);
Auto mapping
Конвенция таблицы 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 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 Apply(IProperty. Instance instance) { if(instance. Property. Name == "Name") { instance. Not. Nullable(); instance. Length(50); } } }
Конвенция свойства с атрибутом public class Max. Length. Convention : Attribute. Property. Convention<Max. Length. Attribute> { protected override void Apply(Max. Length. Attribute attribute, IProperty. Instance instance) { instance. Length(attribute. Value); } }
Конвенция свойства с атрибутом public class Not. Required. Convention : Attribute. Property. Convention<Not. Required. Attribute> { protected override void Apply(Not. Required. Attribute attribute, IProperty. Instance instance) { instance. Nullable(); } }
Конвенция внешнего ключа 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 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 { public void Apply(IOne. To. Many. Collection. Instance instance) { instance. Cascade. None(); instance. Inverse(); instance. Lazy. Load(); } }
NHibernate
Обязательные настройки Название Пример значения 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 Conf. ORM
Настройка Nhibernate. Config-файл <? xml version="1. 0"? > <configuration> <config. Sections> <section name="hibernate-configuration" type="NHibernate. Cfg. Configuration. Section. Handler, NHibernate"/> </config. Sections> <hibernate-configuration xmlns="urn: nhibernate-configuration-2. 2"> <session-factory> <property name="dialect">NHibernate. Dialect. Oracle 10 g. Dialect</property> <property name="connection. driver_class">NHibernate. Driver. Oracle. Data. Client. Driver</property> <property name="connection. provider">NHibernate. Connection. Driver. Connection. Provider</property> <property name="adonet. batch_size">10</property> <property name="proxyfactory_class">NHibernate. Byte. Code. Castle. Proxy. Factory, NHibernate. Byte. Code. Castle</property> <property name="show_sql">true</property> <property name="hbm 2 ddl. auto">update</property> </session-factory> </hibernate-configuration> </configuration>
Настройка 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. 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 = 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 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) { Configuration configuration = new Configuration(); configuration. Data. Base. Integration(dbi => { dbi. Dialect<Ms. Sql 2008 Dialect>(); dbi. Driver<Sql. Client. Driver>(); dbi. Connection. Provider<Driver. 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 configuration = Fluently. Configure() . Database(Ms. Sql. Configuration. Ms. Sql 2008 . Connection. String(connection. String)) . Mappings(mappings => mappings. Fluent. Mappings . Add. From. Assembly. Of<Product. Map>() ) . Build. Configuration(); return configuration; }
Настройка 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<Entity>(); model. Conventions. Add<Table. Name. Convention>(); model. Conventions. Add<Custom. Foreign. Key. Convention>(); model. Conventions. Add<Reference. Convention>(); model. Conventions. Add<One. To. Many. Convention>(); model. Conventions. Add<Column. Convention>(); model. Conventions. Add<Id. Convention>(); 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 { 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 = 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. 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/
My_NHibernate.ppt