1 / 33

Intoduction to NHibernate

Intoduction to NHibernate. Agenda. Overview of NHibernate Models and Mappings Configuration Sessions and Transactions Queries. What is Nhibernate ?. mature, ORM solution for .NET platform free, GNU Lesser General Public License

jamese
Download Presentation

Intoduction to NHibernate

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Intoduction to NHibernate

  2. Agenda • Overview of NHibernate • Models and Mappings • Configuration • Sessions and Transactions • Queries

  3. What is Nhibernate ? • mature, ORM solution for .NET platform • free, GNU Lesser General Public License • mapping an object-oriented domain model to a relational database • home == nhforge.org • files on sourceforge • groups http://groups.google.com/group/nhusers • Commercial support • hibernating rhinos - Ayende Rahien • imeta - Steve Strong, Fabio Maulo

  4. History • started as port of the popular Java O/R mapper Hibernate to .NET • Hibernate was started in 2001 by Gavin King • NHibernate was started around 2003 • ver1.0 mirrored the feature set of Hibernate 2.1 • ver1.2.1, released in 11/2007, features from Hibernate 3 and support for .NET 2.0, stored procedures, generics, and nullable types • ver 2.0 was released 08/2008. Comparable to Hibernate 3.2. .NET 1.1 • ver 3.0 - December 04, 2010 - .NET 3.5. • LINQ support, strongly typed criteria-like API called QueryOver, new AST-based parser for NHibernate'sHQL, ... • http://sourceforge.net/projects/nhibernate/files/NHibernate/

  5. Mappings • mappinga class with XML • Keys, ID generators • table-per-class hierarchy • table per class • table per concrete class • one-to-many relationship • lazy loading collections, lazy loading proxies • settingup a base entity class • handling versioning and concurrency

  6. bidirectional one-to-many class relationships • mappings enumerations

  7. mapping a class with XML • 2x .xsd – intellisense • mapping file - XML - extension .hbm.xml • set Build Action to Embedded Resource !!! • model- collection of classes that will be persisted in the database • persistent class- any class that will be persisted (e.g. Person, Address) • entity class- a persistent class with an ID

  8. entity - an instance of an entity class • POCO- Plain Old CLR Object • POCOs are objects not burdened with inheritance or attributes needed for specific frameworks • all entity classes should be persistence ignorant • strongly held design decisions in NHibernate • Id property - primary key value from the db • persistent object identifier (POID)

  9. Approachesto begin developing an NH application • model-first • create model -> map the model -> generate our database tables from the model and mappings • configuration-first • database-first

  10. Non-insert POID generators • assign an identity to a persistent object without writing the object's data to the db • hilo • guid • guid.comb • guid.native • uuid.hex, uuid.string • counter, increment • sequence, seqhilo

  11. Post-insert POID generators • require data to be persisted to the database for an ID to be generated - strongly discouraged • identity • select (uses natural id) • sequence-identity • trigger-identity • native

  12. table-per-class hierarchy • data for our entire hierarchy is stored in a single table • discriminator column ProductType • distinguish among products, books, and movies • by default, the contains the class name • Eg.Core.Product, Eg.Core.Book, or Eg.Core.Movie • subclass properties as must be nullable • suggested method for mapping class hierarchies

  13. table-per-class • properties of the base class in a shared table • each subclass gets its own table • joined-subclasselement • key element to name the primary key column

  14. table-per-concrete class • each class gets its own table • containing columns for all properties of the class and the base class • there is no duplication of data • union-subclass element

  15. one-to-many relationship • relate one entity to another

  16. Lazy loading collections • data isn'tloaded from the database until it is required by the application • fetch Movie (Id, Name, Description, UnitPrice, and Director, but no Actors) • creates an instance of the Movie object • sets the properties of the Movie object with the data from the db • creates a special lazy loading object that implements IList<ActorRole>, and sets the Actors property • returns Movie

  17. foreach (var actor in movie.Actors) Console.WriteLine(actor.Actor); • lazy loading object is initialized • loads the associated ActorRoledata • disable lazy loading by adding the attribute lazy="false" to the list element

  18. Lazy loading proxies • supports lazy loading through the use of proxy objects public class ActorRole : Entity { public virtual string Actor { get; set; } public virtual string Role { get; set; } public virtual Movie Movie { get; set; } } • proxy object is a subclass of Movie – requirements • Movie cannot be a sealedclass • Movie must have a protected or public constructor without parameters • All public members of Movie must be virtual. This includes methods

  19. choices for the creation of these proxy objects • traditional choice DynamicProxy, part of the Castle • LinFu • Spring.NET • build your own • lazy="false" on the class element of our Movie mapping to disable

  20. Collections • most common types • allcollections may also use the ICollectiontype • custom NHibernate.UserType.IuserCollection

  21. Setting up a base entity class • NH relies on the Equals() to determine equality • application should not be aware of proxy objects • Product instance with an ID of 8 should be equal to a different Product instance or Product proxy with an ID of 8 • transient object is an object that has not been persisted to the db

  22. Versioning and concurrency • optimistic and pessimistic concurrency • version element UPDATE Product SET Version = 2 /* @p0 */, Name = 'Junk' /* @p1 */, Description = 'Cool' /* @p2 */, UnitPrice= 100 /* @p3 */ WHERE Id = '764de11e-1fd0-491e-8158-9db8015f9be5' /* @p4 */ AND Version = 1 /* @p5 */ • If no rows updatedStaleStateException • the entity in memory is stale, or out of sync with the db

  23. DateTime-based version fields • Datetime, DateTime2, timestamp • attribute optimistic-lock • <class name="Product"dynamic-update="true„optimistic-lock="dirty">

  24. Other mappings options • Fluent Nhibernate public ProductMapping() { Id(p => p.Id) .GeneratedBy.GuidComb(); DiscriminateSubClassesOnColumn("ProductType"); Version(p => p.Version); NaturalId() .Not.ReadOnly() .Property(p => p.Name); Map(p => p.Description); Map(p => p.UnitPrice) .Not.Nullable(); }

  25. ConfORM • convention-based mappings • mapper outputs anHbmMappingobject built from our conventions • ConfORM uses conventions and patterns to build a mapping directly from the model • Customizable

  26. Bidirectional one-to-many class relationships • ORMsare designed to overcome the impedance mismatchbetween the object model and the relational model • inverse attribute - determine which end of the relationship controls the foreign key • we must keep both sides of relationship in sync

  27. Mappings enumerations • improperly mapped enumeration can lead to unnecessary updates • by default, NH will map an enumeration to an int • AcctType= AccountTypes.Corporate • AcctTypedatabase field = 2 • int doesn't describe the businessmeaning • store the name of the enumeration value • AcctTypedatabase field „Corporate“ • typeattribute • we tell NHibernate to use a custom class for conversion between .NET types and the database

  28. Configuring NHibernate with App.config • proxyfactory.factory_class • specifies the proxy framework we'll use • dialect • specifies a dialect class that NHibernate uses to build SQL syntax • connection.connection_string_name • references our connection string • adonet.batch_size • group SQL DMLstatements in a single ADO.NET command • mapping- where NHwillsearch for our mappings

  29. components of NH app

More Related