Nhibernatethe Orm For Net Platform 1226744632929962 8

Post on 22-Jun-2015

756 views 4 download

Tags:

Transcript of Nhibernatethe Orm For Net Platform 1226744632929962 8

Samnang Chhun (samnang@wowkhmer.com)Software Engineer, http://tech.wowkhmer.com

Introduction to Object-Relational MappingIntroduction to NHibernateNHibernate BasicsMapping Inheritance hierarchiesAdvanced QueryingAdditional Reading

2

3

Object-relational mapping (aka ORM, O/RM, and O/R mapping) is a programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages (Wikipedia)

Objects are hierarchicalDatabases are relational

4

Objects Relational

ORM

Performance or ScalabilityProductivity: less code to write/maintainAbstraction: transient to different DB technologiesSimplification and ConsistencyQuality: depending on the product

5

ADO.NET Entity Framework (released with .NET 3.5 SP1)Business Logic Toolkit for .NETCastle ActiveRecordIBatis.NetLightSpeedLinq (Language Integrated Query)LLBLGenLLBLGen ProNHibernateNeo …etc

6

7

Initially developed for Javacreated in late 2001 by Gavin Kingabsorbed by the JBoss Group / Red Hat

Ported to .NET 1.1, 2.0, 3.5Resulting product called “NHibernate”

All popular databases supportedOracle, SQL Server, DB2, SQLite, PostgreSQL, MySQL, Sybase, Firebird, …

XML-based configuration filesGood community supportFree/open source - NHibernate is licensed under the LGPL (Lesser GNU Public License)

8

9

RDBMS

ISessionFactoryOne per database (or application)Expensive to create

Reads configurationISession

Portal to the databaseSaves, retrieves

ITransactionEncapsulates database transactions

10

SessionFactory Session Transaction

11

12

<class> declare a persistent class<id> defines the mapping from that property to the primary key column

Specifies strategy<property> declares a persistent property of the class<component> maps properties of a child object to columns of the table of a parent class.Associations

One-to-ManyMany-to-OneMany-to-ManyOne-to-One (uncommon)

13

14

Element Description .NET Type<set> An unordered collection

that does not allow duplicates.

Iesi.Collections.ISetIesi.Collections.Generic.ISet<T>

<list> An ordered collection that allows duplicates

System.Collections.IListSystem.Collections.Generic.IList<T>

<bag> An unordered collection that allow duplicatd

System.Collections.IListSystem.Collections.Generic.IList<T>

15

<class name="Animal"><id name="Id">

<generator class="native" /></id><discriminator column="AnimalType" length="5" /><property name="Name" />

<subclass name="Dog" discriminator-value="Dog"><property name="Breed" />

</subclass><subclass name=“Frog" discriminator-value=“Frog">

<property name=“TongueLength" /></subclass>

</class>

16

ProsSimple approachEasy to add new classes, you just need to add new columns for the additional dataData access is fast because the data is in one tableAd-hoc reporting is very easy because all of the data is found in one table.

ConsCoupling within the class hierarchy is increased because all classes are directly coupled to the same table. A change in one class can affect the table which can then affect the other classes in the hierarchySpace potentially wasted in the databaseTable can grow quickly for large hierarchies. 17

<class name="Animal"><id name="Id">

<generator class="native" /></id><property name="Name" /><joined-subclass name="Dog">

<key column="Id" /><property name="Breed" />

</joined-subclass><joined-subclass name="Frog">

<key column="Id" /><property name="TongueLength" />

</joined-subclass></class>

18

ProsEasy to understand because of the one-to-one mappingVery easy to modify superclasses and add new subclasses as you merely need to modify/add one tableData size grows in direct proportion to growth in the number of objects.

ConsThere are many tables in the database, one for every class (plus tables to maintain relationships)Potentially takes longer to read and write data using this technique because you need to access multiple tablesAd-hoc reporting on your database is difficult, unless you add views to simulate the desired tables. 19

<class name="Frog"><id name="Id">

<generator class="native" /></id><property name="Name" /><property name="TongueLength" />

</class>

<class name="Dog"><id name="Id">

<generator class="native" /></id><property name="Name" /><property name="Breed" />

</class>

20

ProsEasy to do ad-hoc reporting as all the data you need about a single class is stored in only one tableGood performance to access a single object’s data.

ConsWhen you modify a class you need to modify its table and the table of any of its subclasses.

21

22

23

Object oriented queryingIncrease compile-time syntax-checkingEasy to writeHard to read

24

ICriteria crit = sess.CreateCriteria(typeof(Cat)); crit.SetMaxResults(50); List topCats = crit.List();

IList cats = sess.CreateCriteria(typeof(Cat)) .Add( Restrictions.Like("Name", "Fritz%")) .Add( Restrictions.Between("Weight", minWeight,

maxWeight)).List();

String based queryingObject-Oriented SQLSimilar to SQLSpeak in terms of objectsCase sensitiveVery flexibleZero compile-time syntax-checking

25

• from Customer c where c.Name like :name

• select count(*) from Customer c

Powerful way to (simply) return a group of like objects from the DB.

Wonderfully simple to work withGreat way to quickly process a “…where A=<something> and B=<something> and C=<something>…”

26

Cat cat = new Cat(); cat.Sex = 'F'; cat.Color = Color.Black; List results = session.CreateCriteria(typeof(Cat))

.Add( Example.Create(cat) )

.List();

You can submit SQL statements to NHibernate if the other methods of querying a database do not fit your needsutilize database specific features

27

• sess.CreateSQLQuery("SELECT * FROM CATS") .AddScalar("ID", NHibernateUtil.Int32) .AddScalar("NAME", NHibernateUtil.String) .AddScalar("BIRTHDATE", NHibernateUtil.Date);

• sess.CreateSQLQuery("SELECT * FROM CATS") .AddEntity(typeof(Cat));

28

29

Nhibernate.ContribMapping.AttributesCacheSearchValidatorBurrowLINQ to NHibernateShards

Fluent Interface to NHibernate

30

http://en.wikipedia.org/wiki/Object-relational_mappingNHibernate in ActionNHibernate Reference Documentation 1.2.0http://code.google.com/p/sharp-architecture/http://www.codeproject.com/KB/database/Nhibernate_Made_Simple.aspxhttp://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspxwww.hibernate.orgNHibernate FAQSummer of NHibernate

31