SlideShare a Scribd company logo
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=&quot;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: 1 st  level cache Every ISession has an in-built cache called 1 st  level cache Stores all the loaded entities for current unit of work Prevents needless round-tripping to DB
Caching: 2 nd  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

More Related Content

PPTX
NHibernate for .NET
PPTX
NHibernate
PDF
NHibernate (The ORM For .NET Platform)
PPS
Introduction To NHibernate
PPTX
NHibernate
PPT
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
PDF
Advanced SQL - Database Access from Programming Languages
PPTX
Introduction to MongoDB
NHibernate for .NET
NHibernate
NHibernate (The ORM For .NET Platform)
Introduction To NHibernate
NHibernate
Introduction Of Linq , ASP.NET Training Ahmedabad, ASP.NET Course Ahmedabad
Advanced SQL - Database Access from Programming Languages
Introduction to MongoDB

What's hot (19)

PPTX
Hibernate tutorial
PDF
HypergraphDB
PPTX
Entity Framework
PPTX
Object oriented programming 2 elements of programming
PDF
Graph Analytics with ArangoDB
PPTX
Hibernate in Nutshell
PPT
Learn HIBERNATE at ASIT
PDF
PostgreSQL - Case Study
PPTX
Linq
PPTX
Entity framework
PDF
A Graph Database That Scales - ArangoDB 3.7 Release Webinar
PPT
Introduction to hibernate
PDF
Deep dive into the native multi model database ArangoDB
PPTX
Big data
PPT
Entity framework 4.0
PPT
Language Integrated Query - LINQ
ODP
Spring Data in 10 minutes
PPT
ADO.NET Entity Framework
Hibernate tutorial
HypergraphDB
Entity Framework
Object oriented programming 2 elements of programming
Graph Analytics with ArangoDB
Hibernate in Nutshell
Learn HIBERNATE at ASIT
PostgreSQL - Case Study
Linq
Entity framework
A Graph Database That Scales - ArangoDB 3.7 Release Webinar
Introduction to hibernate
Deep dive into the native multi model database ArangoDB
Big data
Entity framework 4.0
Language Integrated Query - LINQ
Spring Data in 10 minutes
ADO.NET Entity Framework
Ad

Similar to Introduction to NHibernate (20)

PDF
Run Cloud Native MySQL NDB Cluster in Kubernetes
PDF
Open Source Storage at Scale: Ceph @ GRNET
PDF
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
DOC
Advanced Hibernate Notes
PDF
Hadoop and object stores can we do it better
PDF
Hadoop and object stores: Can we do it better?
PPT
Connecting to a REST API in iOS
PDF
Ceph Day New York 2014: Future of CephFS
PPT
Hibernate for Beginners
PDF
Big Data Essentials meetup @ IBM Ljubljana 23.06.2015
PPTX
DotNetFest - Let’s refresh our memory! Memory management in .NET
PPT
PPTX
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
PPT
EnScript Workshop
PDF
Michael stack -the state of apache h base
PPT
Persistence hibernate
PDF
Null Bachaav - May 07 Attack Monitoring workshop.
PPTX
Privilege Escalation with Metasploit
PPTX
Introduction to NoSQL Databases
PPTX
Hibernate
Run Cloud Native MySQL NDB Cluster in Kubernetes
Open Source Storage at Scale: Ceph @ GRNET
.NET Fest 2018. Maarten Balliauw. Let’s refresh our memory! Memory management...
Advanced Hibernate Notes
Hadoop and object stores can we do it better
Hadoop and object stores: Can we do it better?
Connecting to a REST API in iOS
Ceph Day New York 2014: Future of CephFS
Hibernate for Beginners
Big Data Essentials meetup @ IBM Ljubljana 23.06.2015
DotNetFest - Let’s refresh our memory! Memory management in .NET
JetBrains Day Seoul - Exploring .NET’s memory management – a trip down memory...
EnScript Workshop
Michael stack -the state of apache h base
Persistence hibernate
Null Bachaav - May 07 Attack Monitoring workshop.
Privilege Escalation with Metasploit
Introduction to NoSQL Databases
Hibernate
Ad

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Spectroscopy.pptx food analysis technology
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Big Data Technologies - Introduction.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Machine learning based COVID-19 study performance prediction
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Spectroscopy.pptx food analysis technology
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Digital-Transformation-Roadmap-for-Companies.pptx
Review of recent advances in non-invasive hemoglobin estimation
sap open course for s4hana steps from ECC to s4
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Big Data Technologies - Introduction.pptx

Introduction to NHibernate

  • 1. Introduction to NHibernate By Andrew Smith
  • 2. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates SQL at run time Database agnostic
  • 3. 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
  • 5. 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”
  • 6. Sessions Very quick to create session Disposable (may hold a DB connection open) Web: session per request. (Also, ‘long conversations’ - check out NHibernate Burrow)
  • 7. 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
  • 8. 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
  • 9. Demo: The basics Fetching single entity by ID Updating Inserting
  • 10. 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”
  • 11. Mappings: 1-* Relations Professor (1) – Class (*) Bi-directional: <bag> and < many-to-one > Declare the many-valued end inverse=&quot;true“ Use ‘ not-found =ignore’ for bad, legacy data
  • 12. Mappings: *-* Relations Student (*) – Class (*) Bi-directional: 2 <bag> elements with link table name Arbitrarily choose 1 end to set as Inverse=“true” Demo
  • 13. 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?
  • 14. 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
  • 15. Querying Lots of options: Criteria DetachedCriteria HQL Linq SQL
  • 16. 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
  • 17. Querying: Projections By default NH selects all mapped properties of entity Projections allow control over the ‘select’ part of generated SQL
  • 18. 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
  • 19. Querying: DetachedCriteria Same capabilities as ICriteria Does not require active session Can be ‘attached’ to any session at any time to execute query
  • 20. Querying: MultiCriteria Enables multiple criteria to be evaluated in the one round trip to DB Very useful for paging
  • 21. Querying: HQL Similar to SQL Allows querying over domain entities “ HQL is fully object-oriented, understanding notions like inheritance, polymorphism and associations”
  • 22. Querying: Linq NHibernate Linq 1.0 released Supports just about anything you can do with criteria API
  • 23. Caching: 1 st level cache Every ISession has an in-built cache called 1 st level cache Stores all the loaded entities for current unit of work Prevents needless round-tripping to DB
  • 24. Caching: 2 nd 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!
  • 25. Querying: Future Queries Executes a batch of queries in one round trip to DB
  • 26. 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
  • 27. 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