Download
getting started with nhibernate n.
Skip this Video
Loading SlideShow in 5 Seconds..
Getting started with NHibernate PowerPoint Presentation
Download Presentation
Getting started with NHibernate

Getting started with NHibernate

124 Views Download Presentation
Download Presentation

Getting started with NHibernate

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Getting startedwith NHibernate Sean Chambers

  2. About Sean • Senior Developer at Flagler County Schools for 5 years • Owner Hybrid Software, Educational Software • Contributor to various open source projects (Castle Project, Nhibernate, NUnit, NBehave) • Practicing TDD,DDD,BDD for 2 years • Blog: http://schambers.lostechies.com •  Twitter: schambers

  3. What is an ORM? • ORM stands for Object Relational Mapper • Maps your POCO (plain old clr objects) to your relational model using XML config • Relieves developer from 95% of common CRUD code

  4. Which database software? • MSSQL 2000, 2005 etc.. • SqlCe, Sqlite, Firebird embedded db’s • MySQL • PostgreSql • Oracle • SyBase • Db2 • Many many more

  5. High level architecture

  6. SessionFactory SessionFactory consumes the configuration Shared among all application threads Instantiation is expensive as parsing of mapping files is performed Validates mapping files, showing errors if incorrect mapping SessionFactory provides Session objects that are used to interactwith the database A Session object holds an open connection to the database forloading objects, and transaction management

  7. Configuration • 1. Web.config/app.config • 2. Mapping files • Configuration defines db dialect, db connection and mapping files assembly • Sample mapping file: <class name=“Order” table=“Orders”> <id name="Id" type=”int" column=“OrderId" unsaved-value="0"> <generator class=”native"/> </id> <property name=“Total” /> <many-to-one name=“Customer” /> </class>

  8. The almighty Session • Manages interaction with database, contains all basic CRUD operations • session.Get(typeof(Order), orderId); • Session.Load(typeof(Order), orderId); will throw exception • session.Save(myOrder); • session.SaveOrUpate(myOrder); • Session.Delete(myOrder);

  9. Querying Options • Query/HQL API • Criteria API • Native SQL

  10. Query API • Nhibernate contains an extremely powerful querying API • IQuery • Provides a method for building a DB query through HQL (hibernate query language) IQueryq = session.CreateQuery(“from Orders where Total>:total”) .SetDecimal(“Total”, 30m) .OrderBy(Order.Asc(“Title”)) .SetFirstResult(20) .SetMaxResults(10); IList<Order> orders = q.List<Order>();

  11. Criteria API • Constructs a query using an API • Is more extensible than HQL ICritieracrit = session.CreateCriteria(typeof(Order)) .Add(Expression.Gt(“Total”, 30m)) .SetFirstResults(20); IList<Order> orders = crit.List<Order>();

  12. Native SQL queries • Allows you to execute native SQL queries • Good for legacy adoption IList<Order> orders = session.CreateSqlQuery(“select {order.*} from Order {order} where {order.Total} < 30.00”), “order”, typeof(Order)) .List<Order>();

  13. Dirty Objects • NHibernate will track changes performed to an object a.k.a. “Dirty” objects • Will implicitly call Save: Order order = session.Load(typeof(Order), orderId); order.Total = 69.95m; session.Flush(); Flush() is also called when transaction is committed

  14. Working with Mappings • Collection Mapping • Component Mapping • Inheritance Mapping

  15. Collection Mapping • One of the more complex aspects of NHibernate • Different collection types: • bag : collection of values that are not distinct • list : collection of values that have an index • set : distinct set of values • map :hash/dictionary. Keys and value • Bag and List map to IList<T>, bag with caveats (add method) • Set maps to Iesi.Collections.Generics.HashedSet<T> • Map maps to IDictionary<K, V>

  16. Component Mapping • Maps an objects associations into a single table • Good for value objects that do not require an identity (DDD) • Customer.Address with Street and City fields would map to: • Table: Street, Columns AddressStreet, AddressCity etc… <class name=“Customer” table=“Customer”> <property name=“FirstName” /> <property name=“LastName” /> <component name=“Address”> <property name=“Street” /> <property name=“City” /> </component> </class>

  17. Inheritance Mapping • Three different strategies for mapping inheritance hierarchies • Table per class hierarchy (1 table total) • Uses a discriminator to identify the type of the row • Will have null values for certain columns • Table per subclass (1+n tables) • One for the base class, one table for each subclass • Table per concrete class (n tables) • No table for the base class

  18. XML Mapping files suck! • Fluent NHibernate • http://code.google.com/p/fluent-nhibernate/ • This tool was just recently forked from Jeremy Miller’s StructureMap

  19. Lazy-Loading • Absolutely necessary with any ORM • Inserts proxies at traversal points • Once navigation to assoc./collection is performed, NHibernate will retrieve data on-the-fly and replace the proxy object • Can modify behavior to “Eager” load related objects • Can be problematic in certain scenarios, namely JSON serialization • Saves you from loading an entire object graph when all you need is a subset of data

  20. When is NHibernate not needed? • Legacy applications • Often, it is difficult to make your model map to your established db structure, not impossible however • ETL/Data Mining scenarios • Small Domain Models/No Domain Model

  21. Generated SQL has got to be slow! • Good post on performance benchmarks:http://www.iamnotmyself.com/2008/07/02/NHibernateTestingThePerformanceUrbanLegend.aspx • Performance benchmark results

  22. Some Samples