210 likes | 344 Views
Object Relational Mapping with NHibernate. Ben Scheirman Principal Consultant Sogeti flux88.com. Why Objects?. Take advantage of . NET Complex business logic is easier to model IntelliSense Fluid interfaces. Focus on Business Logic FIRST. Paradigm Mismatch. Objects are hierarchical
E N D
Object Relational Mapping with NHibernate Ben Scheirman Principal Consultant Sogeti flux88.com
Why Objects? • Take advantage of .NET • Complex business logic is easier to model • IntelliSense • Fluid interfaces Focus on Business Logic FIRST
Paradigm Mismatch • Objects are hierarchical • Databases are relational
The problem of Granularity User ? Address
The problem of Inheritance BillingAccount ? CreditCard CheckingAccount
Why NHibernate? • Mature • Good community support • Good direction • Flexible • Can do POCO
NHibernate in a Nutshell • ISessionFactory • ISession • ITransaction
Hello World with NHibernate Demo time
Key concepts • ISessionFactory is expensive • ISession should be use-case bounded • Open at the start of a unit of work • Close at the end
NHibernate Architecture Business Layer Persistent Classes IInterceptor ILifecycle IUserType IValidatable Persistence Layer ISessionFactory ISession ITransaction IQuery Configuration ADO.NET
How do you GLUE the objects and the database? Foo.cs .NET Object Foo.hbm.xml Mapping XML
Unidirectional One to many A Blog has many Posts Blog IList<Post> Posts; Post 1 * Blog.hbm.xml <bag name="Posts"> <key column="BlogId" /> <one-to-many class="Post" /> </bag>
Bidirectional Many-to-Many A category has items, an item has categories Item ISet Categories Category ISet Items * * Item.hbm.xml <set name="Categories" table="Item_Categories"> <key column="ItemId" /> <many-to-many class="Category" /> </set> Category.hbm.xml <set name=“Items" table="Item_Categories“ inverse=“true”> <key column=“CategoryId" /> <many-to-many class=“Item" /> </set> What is INVERSE?
Understanding INVERSE Post p = new Post(); Category cat = new Category(); p.Categories.Add(cat); cat.Posts.Add(p); UPDATE Post_Categories(PostId, CategoryId) VALUES(@p, @c) UPDATE Post_Categories(PostId, CategoryId) VALUES(@p, @c) One side needs to “Manage” the association
Understand Lazy-Loading • Default Behavior • Lazy for Objects • Lazy for Collections
Blogging with NHibernate Demo time
What’s the first step? • The object model, of course! Blog Post * Categories * 1 * 1 * Comments
ASP.NET ISession Management • Session-per-Request pattern Page IIS A S P .N E T Http-Module A web request Create / Destroy Use HttpContext ISession
Resources • ayende.com/blog • Hibernate in Action • NHibernate in Action (pre-release PDFs) • NHibernate Forums • Castle Project (Active Record)