introduction to nhibernate by andrew smith. the basics object relation mapper maps pocos to database...
TRANSCRIPT
Introduction to NHibernate
By Andrew Smith
The Basics
• Object Relation Mapper
• Maps POCOs to database tables
• Based on Java Hibernate. V stable
• Generates SQL at run time
• Database agnostic
Entity definitions
• “Persistence ignorance”– No need for special base class– No need to implement special interfaces
• Default constructor• Identity property (Primary key)• To support lazy loading, public properties
and methods must be virtual• Collection properties must be declared as
an interface type
Class Diagram
Configuration
• Multiple options – Xml, ActiveRecord, Fluent NH
Xml:• 1 overall configuration section• Multiple “<entityname>.hbm.xml”
embedded resource files• Intellisense: Place .xsd files in “Microsoft
Visual Studio 9.0\Xml\Schemas”
Sessions
• Very quick to create session
• Disposable (may hold a DB connection open)
• Web: session per request. (Also, ‘long conversations’ - check out NHibernate Burrow)
Mappings: Primary keys
• Entities must be identifiable
• Multiple strategies for PK
• Use ‘native’ as best-guess
• Recommended way is “HiLo” to save round-tripping to DB
Mappings: Properties
• Maps database columns to properties/fields on entity
• Can map columns to nested types
• Control insert/update per column
• Default is to insert/update all columns, but can be dynamic
Demo: The basics
• Fetching single entity by ID
• Updating
• Inserting
Mappings: Relations
• Many types. Most common: bag and set
• Assuming bi-directional relations and simple bag collections
• In a bi-directional association, only one end can be the ‘owner’
• Identify the ‘non-owner’ end of collection by setting Inverse=“true”
Mappings: 1-* Relations
• Professor (1) – Class (*)
• Bi-directional: <bag> and <many-to-one>
• Declare the many-valued end inverse="true“
• Use ‘not-found=ignore’ for bad, legacy data
Mappings: *-* Relations
• Student (*) – Class (*)
• Bi-directional: 2 <bag> elements with link table name
• Arbitrarily choose 1 end to set as Inverse=“true”
• Demo
Cascades
• Don’t have to explicitly call save / update / delete on related entities
• Cascade types: none, save-update, delete, all, all-delete-orphan
• Can define a default cascade
• Q’s?
Proxies
• Enables lazy loading - Just in time loading of data– Lazy loaded collections– Lazy loaded entities (the single-end of a
relation)– Controlled via mappings or code
• Watch for N+1 issue
Querying
• Lots of options:– Criteria– DetachedCriteria– HQL– Linq– SQL
Querying: ICriteria
• Out-of-the-box method for building up a query in code
• Requires an active session
• Weakly typed
• nhlambdaextensions project adds typesafe lambda expressions
Querying: Projections
• By default NH selects all mapped properties of entity
• Projections allow control over the ‘select’ part of generated SQL
Querying: Aliases / Subcriteria
• Alias relations to refer to them later
• Need to use them to reference multi-level relations. E.g. OrderItem.OrderHeader.Customer.Name
Querying: DetachedCriteria
• Same capabilities as ICriteria
• Does not require active session
• Can be ‘attached’ to any session at any time to execute query
Querying: MultiCriteria
• Enables multiple criteria to be evaluated in the one round trip to DB
• Very useful for paging
Querying: HQL
• Similar to SQL
• Allows querying over domain entities
• “HQL is fully object-oriented, understanding notions like inheritance, polymorphism and associations”
Querying: Linq• NHibernate Linq 1.0 released• Supports just about anything you can do with criteria API
Caching: 1st level cache
• Every ISession has an in-built cache called 1st level cache
• Stores all the loaded entities for current unit of work
• Prevents needless round-tripping to DB
Caching: 2nd level cache
• Cache shared between sessions• Out of the box support for:
– NHibernate.Caches.Prevalence – NHibernate.Caches.SysCache (ASP.Net cache)– NHibernate.Caches.SysCache2 (SQL
dependency-based expiration)– NHibernate.Caches.MemCache
• Does all the hard work for you!
Querying: Future Queries
• Executes a batch of queries in one round trip to DB
Why use it?• Reduces repetitive, error prone data access code• Enables use of OOP• Very flexible• Stable, widely used• Speed up development time
• Single place to add behaviour such as auditing / INotifyPropertyChanged / Filters etc
• Testing: Easier integration tests• Security: Uses parameterised queries by default
Resources
• Book: NHibernate In Action (v 1.2)
• NHForge.org– NHibernate blog
• Nhibernate FAQ blog
• Very active users group (nhusers)
• ayende.com
• Dimecast and “Summer of NHibernate” videos