NHibernate 2 Beginner’s Guide – Book Review
Finally someone has written an in depth beginners book for nhibernate. Nhibernate 2.0 Beginners Guide written by Aaron Cure is just that and more. Wow do I sound like a car salesman. I was a little disappointed when I read Nhibernate In Action last year, because it was more of a reference than a tutorial. This book is definitely what the title states, which is a beginners guide. The book contains step by step examples of how to find, setup, and use nhibernate. I highly recommend this book to anyone wanting to learn nhibernate. By the way I think all .netters should do just that.
Pros
- love the beginning paragraphs
- In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead of writing reams of SQL statements or creating stored procedures that “live” in a different place than our code, we can have all of our data access logic contained within our application.
With a few simple “tricks” that we’ll discuss in Chapter 4, Data Cartography, not only will our queries be effective, but they will also be validated by the compiler. Therefore, if our underlying table structure changes, the compiler will alert us that we need to change our queries!
- In simple terms, NHibernate does all the database work, and we reap all the benefits! Instead of writing reams of SQL statements or creating stored procedures that “live” in a different place than our code, we can have all of our data access logic contained within our application.
- starts slow, which is perfect for a “beginners” book. lots of hand holding and explanations of basics. this is truly meant for somehow with no experience with ORMs.
- clearly shows you how to use log4net! great bonus in a nhibernate book.
- briefly mentions all the major players in the nhibernate world, which is great for demonstrating options
- Examples: fluent nhibernate, nhibernate.burrow, castle, spring ioc, etc.
Cons
- book uses basic aspx pages with custom controls in the examples. I firmly suggest ASP.Net MVC over webforms. But it may be too much to learn at one time if you aren’t familiar with either nhib or MVC. So learn one first and then learn the other. You won’t regret it.
- most examples are in c# and vb.net. that’s good or bad depending on your opinion of vb.net.
- No HQL examples. All query examples use the Criteria class. This isn’t totally bad especially for beginners, but HQL should have at least been mentioned.
Chapter Notes
- chapter 1
- clearly denotes which version of nhib the book uses and where to get it
- Even explains the nhib release verbiage of “generally available”
- shows basic examples of mapping file and how it relates to POCOs. Good stuff for a ORM newbie.
- clearly denotes which version of nhib the book uses and where to get it
- chapter 2
- good advice for designing your database in logical way that avoids data duplication.
- clear steps to download and setup a database using sql server express
- Does mention that nhib works in almost any database, however all the book examples use sql server express
- nice explanation of how tables relate to your classes
- great introduction to OTM, MTO, MTM, and OTO relationships
- good summary of left joins and how joins matter in queries for the different relationship types
- chapter 3
- starts creating a simple class library application. clear steps and good examples.
- even addresses the somewhat hated nullable types and how to handle database columns that need to be mapped to types that can be null.
- chapter 4
- nice explanation of what mapping means in terms of ORM software and how it functions as the glue that binds your objects to the database.
- summary and examples of the most common used mapping types
- gives examples of two mapping styles
- xml
- lists the two main complaints which are.. 1) too much xml 2) xml files are not compiled, so you don’t find bugs until run time.
- provides great tip of adding the hibernate XSD to your project so that visual studio will provide code completion for you and validate your mapping files.
- important info about how to make sure the xml mapping files are compiled into your dll
- fluent nhibernate
- short example given that shows how using the “side” project http://fluentnhibernate.org/ can work without the xml mapping files.
- pro is that mappings have to be compiled, so bugs/typos are found earlier
- xml
- chapter 5
- creates console application to test the nhib code
- shows step by step how to add references to the nhib dlls that you need to download
- good definition of what a nhib session is and how it relates to an actual database session
- chapter 6
- why you should and how to use log4net with your nhib project
- excellent and thorough tutorial for using log4net
- chapter 7
- nhib config details
- mentions how easy it is to change databases by simply changing one config line
- shows how to config nhib in an app.config or web.config
- chapter 8
- provides example of Singleton DOA pattern
- shows example of using a structure that holds all the column/property names for a class/entity. this is done so that the column names in the structure can be used in criteria queries. all this effort is done to avoid run time exceptions. seems like a waste of time to me because you if you don’t update your structure every time your db is updated then you will still get runtime errors.
- query examples using Criteria (at this point all examples have been using Criteria, none in HQL)
- chapter 9
- in depth examples showing how to create custom controls to display data retrieved using nhibernate
- chapter 10
- shows how to implement the login controls with nhibernate
- chapter 11
- covers 11 code generation tools used to limit manual boiler plate coding. I actually hadn’t heard of many of the ones listed. Great bonus chapter.
- nhib-gen, mygeneration, NGen NHibernate Code Generator, and T4 hbm2net seem promising
- these tools create everything from POCOs to DAOs to services.
Managing Unmapped Tables with Hibernate
There’s an underused feature of Hibernate that I’ve been using recently called “auxiliary database objects“. With these guys, you can finally let Hibernate manage all of your schema creation and deletion. No more using Hibernate to generate mapped tables and then coming behind with another tool to finish the job.
A good example of where this is useful is in the fairly common case of using Quartz for scheduling with a JDBC job store. Quartz provides a SQL script for generating its tables. Before auxiliary database objects, the most common way to get the Quartz tables into the database was to include a separate *.sql file in your build and run it using Ant’s sql task or some other SQL executor. Setting it up this way means there are two steps to either creating or dropping your schema: the Hibernate schema export and the Ant task. That ties this mechanism specifically to your build, eliminating a very useful feature of Hibernate.
With auxiliary database objects, you can include the Quartz create and drop scripts directly in your Hibernate mappings and have Hibernate run those scripts along with its normal schema export. Then there’s only one step to creating and dropping your schema, and more importantly, Hibernate is completely in control of the schema. This gives you the immense benefit of being able to set the SessionFactory’s “hbm2ddl.auto” property to “create” and run an in-memory database–like the awesome H2 database–for development and unit testing, and the schema will be generated for you on startup. This is what you lose if you have scripts outside of Hibernate.
Auxiliary database objects have actually been around for a few years, but it only made it into a general availability release a year and a half ago with version 3.2.6.GA. Below are a couple of simple examples on how to use them.
Besides Quartz tables, I’ve used auxiliary database objects to make a fake “dual” table. It’s common to use the “select * from dual” query on Oracle databases as a validation query for your connection pool. When you run a different database for development, like H2 or MySQL, you’ll have to manually add a dual table so that your validation queries won’t fail. Here are the two ways that you can do that using Hibernate’s auxiliary database objects:
First, you can embed the SQL directly in the mapping file:
<hibernate-mapping>
<database-object>
<create>
create table dual (x int);
</create>
<drop>
drop table dual;
</drop>
<dialect-scope name="org.hibernate.dialect..." />
</database-object>
</hibernate-mapping>
Note that you can have zero to many of the dialect-scope elements, indicating what database platforms this database object applies to. Listing zero dialects means apply to all databases.
The second way to do it is to implement the AuxiliaryDatabaseObject interface. To make it simple, use the AbstractAuxiliaryDatabaseObject subclass:
public class SampleObject extends AbstractAuxiliaryDatabaseObject {
public String sqlCreateString(...) {
return "create table dual (x int)";
}
public String sqlDropString(...) {
return "drop table dual";
}
}
Then you have to specify your class in your mapping file, like so:
<database-object>
<definition class="rds.hibernate.AuxDBObjectTest" />
<dialect-scope name="org.hibernate.dialect..." />
</database-object>
The examples should be pretty self explanatory. Create statements are run after Hibernate’s own generated create statements, and drop statements are run after Hibernate’s generated drop statements. I’ll make one additional recommendation: while it’s technically possible to put multiple SQL statements separated by semicolons in a single create or drop block, it’s best to only put one. There are two reasons for this. First, multiple statements in a single block won’t work with Oracle, so if any of your target environments are Oracle, that’s right out. The second reason is that Hibernate runs each create and/or drop using one JDBC Statement, so if you pack 100 create statements into one create block, and one of them fails, then none of the other 99 will take affect, either. If, on the other hand, you use one statement per block, you guarantee that all statements will run, and only the ones that fail will not take effect.
That’s all! It’s very handy to have all your extra SQL managed by Hibernate. All you have to do is point Hibernate at a database, tell it to create your schema, and all your tables, views, stored procedures, etc. will appear.
If You Want to Have Cities You’ve Got to Build Roads
I wrote this for consideration for the upcoming 97 Things Every Programmer Should Know book. Alas, I didn’t submit it before the deadline. I’m OK with that that because I had another submission that I think has a good chance to make it in the book.
I particularly like to apply this phrase in every-day software development and could easily apply it to entrepreneurship.
The city of Rome has a history of over two and a half thousand years. The city was the center of the Roman Empire and was the capital of the civilized world. It supported hundreds of thousands of inhabitants only by providing the proper foundation for the city. Its roads.
The roads of the Roman city were essential for the growth of the Empire. These roads were used to move goods and services enabling its citizens to prosper. The Roman armies used these roads to defend the Roman territories and to conquer new lands. The roads provided a network for information to be gathered and disseminated. The Roman roads were critical in for its expansion. Roads were the foundation of this great city.
When you think of Rome, you don’t think about its roads. But what would Rome have been without its roads. How big could it have grown? How could the armies defend the Empire? The Roman roads were required for the city to thrive. The roads are not what made the city great, but were what made the city’s success a possibility.
Every organization has its roads and your organization is no exception. What infrastructure have you put in place to foster the growth of your business and lead to its success? Do you have any infrastructure at all? How far can your organization proceed without this infrastructure?
Perhaps for you this is how you communicate. Not just among your team but with your organization, with your customers, and with your community. It could be how you notify your users of new features, how your users submit bugs, or how your managers communicate deadlines.
Maybe its not communication but your product management. From your code repositories and automated build processes to your deployment and monitoring suites. These might be the factors that contribute to the ultimate success of your organization. Without the proper infrastructure in place the city will fail or cease to grow. Without the roads Rome could not prosper and without a strong foundation your organization will fail or hit a wall.
If your users can not submit bugs they will be forced to use your product day after day with known issues. They will become frustrated and find alternative software. If your organization can not communicate its goals and strategies with you then you can not support your organization and so it will fail.
Find out what it is the supports your organization and fortify it. Be aware of its presence and its importance.
With that said, also consider this: the Roman’s roads played an important part in the Roman military defeat by offering avenues of invasion to the barbarians.
From If You Want to Have Cities You’ve Got to Build Roads
