You are previewing Learning NHibernate 4.
O'Reilly logo
Learning NHibernate 4

Book Description

Explore the full potential of NHibernate to build robust data access code

In Detail

Connecting the object-oriented world of .NET to the relational world of databases has always been fiddly but with the onset of ORMs such as NHibernate, developers have finally got some relief in this area.

You will begin with a bird's eye view of NHibernate, touching upon its core concepts. You will define domain model and map it with database schema using different techniques. You will then look into multiple ways of storing domain entities in a database and learn important concepts such as transitive persistence, transactions and unit of work. This will be followed by retrieving data from database. Next, you will optimize your code, explore concepts such as the onion architecture, and learn where NHibernate fits best in an application's architecture. After introducing a well-known repository pattern into our application, you will learn to deal with legacy databases. We will conclude with infrequently used features such as stateless sessions, the second level cache, concurrency, and so on, which might come handy.

What You Will Learn

  • Map domain entities to a database schema using the different mapping mechanisms available

  • Configure NHibernate through XML configuration

  • Save, update, and delete entities in the database and query data from a database using different querying methods

  • Optimize database operations for speed and memory consumption

  • Use NHibernate in real-life software projects

  • Get to know about data access patterns such as repository, specification, and query object

  • Use NHibernate with legacy databases

  • Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

    Table of Contents

    1. Learning NHibernate 4
      1. Table of Contents
      2. Learning NHibernate 4
      3. Credits
      4. About the Author
      5. About the Reviewers
      6. www.PacktPub.com
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
      7. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      8. 1. Introduction to NHibernate
        1. What is ORM?
        2. What is NHibernate?
        3. What is new in NHibernate 4.0?
        4. NHibernate for users of Entity Framework
        5. Is using ORM a bad idea?
          1. Why ORM is a better bet?
          2. Non-functional features required by the data access layer
        6. Building blocks of NHibernate
          1. Mappings
          2. Configuration
          3. Session
        7. Summary
      9. 2. Let's Build a Simple Application
        1. Explaining the approach used in learning NHibernate
        2. The problem statement
        3. The development setup
          1. Visual Studio 2013
          2. SQL Server 2012 Express
          3. ReSharper
          4. NUnit
          5. NuGet
          6. SQLite
        4. The domain model
          1. Employee
          2. Leave
          3. SeasonTicketLoan
          4. SkillEnhancementAllowance
        5. Adding some code
          1. Adding the NuGet packages to projects
          2. Back to our test
        6. Summary
      10. 3. Let's Tell NHibernate About Our Database
        1. Important NHibernate terminology
        2. Mapping the prerequisites
        3. Different mechanisms to write the mappings
          1. XML mappings
          2. Fluent mapping
          3. Mapping by code
        4. XML mappings for the Employee class
          1. Getting the development environment ready
          2. Getting IntelliSense to work with the XML mapping files
          3. Unit tests to verify the Employee mappings
          4. The mappings
            1. Hibernate-mapping
            2. Class
            3. Property
        5. Identifier generation
          1. Identity
          2. Sequence
          3. Hilo
          4. Seqhilo
          5. GUID
          6. Guid.comb
          7. Native
          8. Assigned
        6. Mapping associations
          1. Associations and database tables
          2. One-to-many association
            1. Types of collections
          3. Many-to-one association
          4. One-to-one association
          5. Many-to-many association
        7. Mapping inheritance
          1. Unit tests to verify the inheritance mappings
          2. Table per class hierarchy
          3. Table per subclass
          4. Table per concrete class
          5. Choosing the right inheritance mapping strategy
        8. Mapping components
        9. Mapping by code
          1. Identifier
          2. Property
          3. Association
            1. One-to-many
            2. Many-to-one
            3. One-to-one
            4. Many-to-many
          4. Component
          5. Inheritance
            1. Table per class hierarchy
            2. Table per subclass
            3. Table per concrete class
          6. Complete mappings by code for the employee benefits domain
        10. Fluent mapping a.k.a. Fluent NHibernate
          1. Inheritance mappings
            1. Table per class hierarchy
            2. Table per concrete class
            3. Table per subclass
          2. Component mapping
        11. Choosing the right mapping method
        12. Summary
      11. 4. NHibernate Warm-up
        1. Warming up NHibernate succinctly
        2. The NHibernate session architecture
        3. XML configuration
        4. Programmatic configuration
        5. Loquacious configuration
        6. Fluent configuration
        7. Configuration options
          1. Connection release mode
          2. Dialect
          3. Driver
          4. Mappings
            1. Programmatic configuration
              1. XML mapping
              2. Mapping by code
            2. Fluent configuration
          5. Connection string
          6. Caching
          7. Session context
          8. Batch size
          9. Command timeout
          10. Show SQL
        8. Generating the database scripts from mappings
          1. The database creation script
          2. The database update scripts
          3. Automatically create/update the database schema
        9. Summary
      12. 5. Let's Store Some Data into the Database
        1. Entity states
        2. Transactions and unit of work
          1. Explicit and implicit transactions
          2. Flush modes
        3. Saving entities
          1. Saving entities – complex scenarios
        4. Transitive persistence using cascade styles
        5. Transitive persistence/cascading in action
          1. Saving a transient entity with association to other transient entities
            1. A word on bidirectional associations
          2. Updating associations on a persistent entity
          3. Deleting a persistent entity with one or more associations set
        6. Bidirectional associations and ownership
          1. Ownership in many-to-many associations
            1. Inverse and cascade
        7. Order of operations
        8. Entity equality
          1. Why does equality matter?
          2. Implementing equality
        9. The architecture diagram
        10. Summary
      13. 6. Let's Retrieve Some Data from the Database
        1. Querying the workflow
        2. Different querying methods
          1. Native SQL
          2. Hibernate Query Language
            1. Parameter binding
          3. Criteria API
            1. Filtering the criteria queries
          4. The QueryOver API
          5. LINQ
          6. Which querying method should I use?
        3. Joins
          1. Different types of joins
          2. Implicit joins
            1. QueryOver joins explained
              1. JoinAlias
          3. Outer joins
          4. Theta style joins
        4. Lazy loading
          1. Lazy collections
            1. Disabling laziness
            2. Different lazy behaviors
          2. Single-ended lazy associations
            1. Proxy versus NoProxy
          3. Lazy properties
          4. Why use lazy loading?
          5. Lazy loading gotcha's
            1. Keeping the session open
            2. Being aware of the select N+1 problem
            3. Using lazy loading together with the right fetching strategy
            4. Using automatic properties
        5. Eager fetching
          1. HQL
          2. Criteria
          3. QueryOver
          4. LINQ
        6. Pagination and ordering of results
          1. Narrowing down the number of records returned by a query
          2. Ordering the results
        7. Retrieving entities by identifiers
          1. Why use Load<T>?
        8. Polymorphic queries
        9. Summary
      14. 7. Optimizing the Data Access Layer
        1. Baseline and optimize
        2. Organization of the chapter
        3. Batching
          1. Batching the write queries using ADO.NET batching
            1. Limitations of batching
            2. Memory consumption and batching
          2. Read batching using future queries
          3. Batching lazy collections
        4. Fetching strategies

          1. Select fetching
          2. Join fetching
          3. Subselect fetching
          4. Choosing the right fetching strategy
        5. Avoiding the select N+1 problem
          1. What is the select N+1 problem?
          2. Why select N+1 is a problem?
          3. How do we fix the select N+1 problem?
        6. Avoiding eager fetching
          1. Future queries to the rescue
        7. Using extra-lazy for lazy collections
        8. Summary
      15. 8. Using NHibernate in a Real-world Application
        1. What kind of application are we building?
        2. Architectural principles we will follow
          1. No anaemic domain model
          2. The onion architecture
          3. Dependency inversion
          4. Explicitly declaring the capabilities required
          5. Unit of work
        3. Feature 1 – onboarding an employee
          1. Repository pattern
          2. Where does the repository belong?
          3. Back to onboarding an employee
        4. Unit of work
          1. Scope of unit of work for web applications
          2. Session per request
          3. Contextual sessions
          4. Configuring CurrentSessionContext
          5. Implementing session per request using the contextual sessions
            1. Using the HTTP module
            2. Using hooks in the global.ascx file
            3. Using the action filters of ASP.NET MVC or Web API
            4. WCF
          6. Unit of work implementation
            1. Unit of work spanning the whole HTTP request
            2. Unit of work with custom scope
        5. Feature 2 – updating the details of an employee
          1. Updates using transitive persistence
          2. Updating the detached entities
          3. Why transitive persistence is better
        6. Feature 3 – searching employees
        7. Summary
      16. 9. Advanced Data Access Patterns
        1. Problems with the repository pattern
          1. Generalization
          2. Unclear and confusing contract
          3. Leaky abstraction
          4. God object anti-pattern
        2. Specification pattern
          1. Specification pattern in its original form
          2. Specification pattern for NHibernate
          3. Specification chaining
          4. Limitations
        3. Query object pattern
          1. Extending the query object pattern
          2. The limitations of the query object pattern
        4. Summary
      17. 10. Working with Legacy Database
        1. Composite IDs
          1. Composite foreign key
        2. Components
        3. Join-mapping to load data from multiple tables
        4. Working with database views
        5. Using subselect instead of views
        6. Working with stored procedures
        7. Using custom DTOs
          1. Right place for DTOs
          2. The conversion layer
          3. Downsides of using custom DTOs
          4. Custom lazy loading retention
        8. Summary
      18. 11. A Whirlwind Tour of Other NHibernate Features
        1. Concurrency control
          1. Optimistic concurrency control
            1. Using optimistic-lock
            2. Using the version property
          2. Pessimistic concurrency control
        2. Event system
          1. Event listeners
          2. Adding the audit trail for entities
        3. Caching
          1. Session level cache
          2. Second level cache
          3. Query cache
        4. Stateless sessions
        5. User-defined types
          1. Other user-defined types
        6. Summary
      19. Index