Forgot your password?
typodupeerror
Image

NHibernate 3.0 Cookbook 72

Posted by samzenpus
from the read-all-about-it dept.
RickJWagner writes "Are you a .Net developer? Do you have to persist your application objects to a database? If so, I know of a book you might be interested in, Packt Publishing's NHibernate 3.0 Cookbook. NHibernate is a port of the popular Hibernate object-relational mapper (ORM, for those who like TLAs.) An object-relational mapper is a framework that lets the developer get and retrieve application state from a database, and it does so in an efficient, non-intrusive, and flexible manner. Hibernate is the top of the line ORM implementation, yet it's easy enough to learn that even a newbie will find it easy to get started." Read on for the rest of Rick's review.
NHibernate 3.0 Cookbook
author Dentler Jason
pages 328
publisher Packt Publishing
rating 7/10
reviewer RickJWagner
ISBN 184951304X
summary The ultimate "how-to" reference for NHibernate 3.0
This book is written in Packt's 'Cookbook' style, which means it's really a series of how-to templates that guide the reader through some goal-centric activity. A 'recipe' is a formula for accomplishing something, like setting up a session for a web application, or using a profiler with NHibernate, or creating a validator class. You may not know what some of these things do-- but you will when you read the recipe! Each recipe follows a repeated pattern, with sub-sections "Getting Ready", "How to do it", "How it works", "There's More". At first glance, this can be a little deceptive for readers of technical books-- there's really no lengthy text sections that explain the basics of the tool in the early chapters of the book. You might be lulled into thinking this means there's no explanation for how things work, but that would be wrong! The truth is, there is plenty of good NHibernate theory and explanation, it's just that it's contained within the "How it Works" and "There's More" section of each instructional section, not in a chapter devoted to overview just by itself. For this reason, I'd urge bookshelf browsers to be sure to read one topic through front-to-back thoroughly, to get a feel for how the book presents theory as well as practical hands-on-the-keyboard instruction.

As far as content goes, there is a lot of useful content in this book. The author presents 70 different recipes for activites that range from the basic (i.e. your first class-to-database mappings) to the unusual (i.e. using NHibernate Spatial for solving distance-related problems.) The author offers plenty of good text in most of these, but again-- don't be upset by the placement of the high-level material. It's all there, it's just placed a little differently than what you'd find in most technical books.

The book is easy to read. The text is plain and straight to the point, and the author's writing style is quite readable. The code examples are likewise clean and well-formatted. (By the way, I'd urge you to go to Packt's site to get the source bundle if you buy the book. There's a lot of code referenced, you certainly wouldn't want to type it all by hand if you can get it handed to you.) The book runs a little over 300 pages, and most of the type is generously spaced. This is not a strong theoretical reference, but it is more than adequate as a primer for the vast majority of the tasks you'd want to accomplish with NHibernate.

So who is this book good for? I'd give it high marks for .Net developers who want to use NHibernate, regardless of experience level with the tool. I say that because there are enough use cases presented that there is almost certainly a subset of new material for almost anyone. How about Java Hibernate users? I think it's a decent book for them-- NHibernate is a very close port of the base product, so a Java user can get something out of this book, too. (For that crowd, this would obviously not be a good primary choice, but is worthwhile reading if you already have a Java go-to reference for Hibernate.) For anyone else wanting a good high-level overview of ORM use-- I'd say this book is only of marginal value. This is because the bulk of the explanatory material is presented in the context of 'how to' accomplish some particular task and isn't easily accessible without skipping from recipe to recipe.

By the way, lest you think NHibernate is only for .Net devs, I mostly ran the code samples under MonoDevelop on Ubuntu. This was my first adventure with MonoDevelop (the open source IDE for Mono, which itself is an open source, multi-platform port of .Net.) I was pleasantly surprised by the level of polish in the development environment, it really is a nice environment. Again, if you're a Java developer, I'd consider this book a decent learning supplement but would not recommend it as a primary for Hibernate proper.

You can purchase NHibernate 3.0 Cookbook from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

*

This discussion has been archived. No new comments can be posted.

NHibernate 3.0 Cookbook

Comments Filter:
  • Packt Publishing? (Score:1, Insightful)

    by Anonymous Coward

    Packt Publishing == $hill review == Slashvertisement.

    • Re: (Score:1, Insightful)

      by Anonymous Coward

      aren't pretty much all book reviews shashvertisements?

    • Re: (Score:1, Insightful)

      by Anonymous Coward

      Packt Publishing == $hill review == Slashvertisement.

      Amen brother.

      There's one great way you can tell a shill that you think he does a great job, that you approve of deceptive advertising and would love to see more of it, that you support astroturfing, and that lying to customers by telling them that a biased advertisement is really an unbiased book review is perfectly acceptable. If you want to do all of the above, you can buy whatever products they're hawking.

      This quote about TV is true because of two forces: advertising and PR. If you want it to be

  • Take a look at the Castle Project [castleproject.org], which implements Active Record on top of nHibernate.

    It's very nicely done.

    • I'm still holding a grudge against them for Monorail.

      Let's throw away the useful parts of ASP.NET while still keeping its overhead, in order to make writing the kinds of web apps that already aren't very hard faster and the kinds of web apps that are interesting impossible to create! And while we're at it, let's put most of the useful documentation in videos instead of something sensible.

      Disclaimer: I worked with it circa '07 and it may not be as rage-inducing now.

  • In Soviet Russia, we had gross government propaganda. Now, in Free Capitalist America, we have access to much better, and more refined marketing techniques. And it's all you can eat!
  • Running Franticly (Score:5, Informative)

    by GWBasic (900357) <slashdot@and[ ]r ... m ['rew' in gap]> on Wednesday November 17, 2010 @04:26PM (#34259780) Homepage

    I had the misfortune of developing with NHibernate. The root of the problem was that the engineers who started the project didn't know anything about database programming and just used NHibernate as a magic persistance layer. (These guys would write foreach loops that would suck most of the database into RAM.) Ultimately, as I learned the tool, I found that it just makes data access more complicated then it needs to be. In order to use it right, you have to know the underlying database programming concepts, which are simpler and easier to learn then the NHibernate library.

    To make matters worse, when I used NHibernate, there was a bug in runtime code generation, which was very hard to track down and impossible to fix.

    My opinion: Stick with a simple ADO -> Object mapper and write queries as-needed. If you use NHibernate, stick with the basic CRUD features. Don't rely on a more complicated library to handle things like transactions, lazy-loading, and relationship mapping. Be very careful introducing relationships into the business objects, especially automatically-populated ones. And, whatever you do, if you end up working in a project where the senior engineers and/or people who started the project treat NHibernate as a "magic persistance layer," RUN!!!

    Oh, and if you work on a project that wants a "magic persistance layer," because the engineers don't get databases, investigate document databases like MongoDB, Couch, ect. The document model maps a lot better to the object-oriented way of doing things, thus it's a lot harder for programmers who don't get databases to screw them up.

    • Yep, agree. SQL queries work and are easy to debug.
    • Re: (Score:3, Interesting)

      by fusiongyro (55524)

      I agree completely. I'm glad you wrote this. I wish more people would take this advice to heart.

      My situation at work is identical, except with Java and regular Hibernate. My predecessors used Hibernate figuring they could ignore the database. I came in long afterwards. I've spent the last month trying to improve the situation with Hibernate, but there's only so much that can be done when your codebase assumes that all your objects are always in memory.

      Without wanting to distract too much from what comes clo

      • Re: (Score:2, Insightful)

        by eennaarbrak (1089393)

        My predecessors used Hibernate figuring they could ignore the database

        And there is the problem. Hibernate's designers never claimed that you could ignore the database. In fact, one of the biggest strengths of Hibernate is the fact that it does not hide the database away from you - an area where some other ORM tools (like JDO) falls flat.

        ... there's only so much that can be done when your codebase assumes that all your objects are always in memory

        Hibernate does not promote this view of persistence at all. It has a clearly defined object lifecycle and state model which allows specific control over how your entities interact with the database. Seems like you are blaming Hibernate for

        • I must agree with the parent. nHibernate has allowed me to save countless hours writing CRUD.
          Using FluentnHibernate helped even more.
          Was there a learning curve for both of these? You bet your ass there was.
          Was it worth it? hell yes. I use nHibernate in every project I can.
          Was the learning curve shorter than just writing all the crud? I don't think so. But no one should expect miracles from their first nHibernate implementation.
          You'll see some benefits, but the big benefits will probably come in on you

      • by GWBasic (900357)

        Another thing to consider is OODBs. I'm going to be looking at db4o pretty soon because this situation is just intolerable. I had a call with Objectivity, but they wanted in the neighborhood of $80K for a 100 client installation on a 4 processor machine with 3 developer licenses, and that's way beyond our budget. Would have probably been perfect for our situation though, due to the way they wrote the code.

        Be careful with DB4o. I played with in in 2005-2006, and its object-loading scheme was somewhat confusing. You need to "know" that your in-memory objects can be incomplete, which means that you continually need to activate them.

        MongoDB, with their C# drivers, is a very similar "sales pitch" to Objectivity. Both the MongoDB and Objectivity drivers let you work with real C# objects. The reason why I like MongoDB, (in addition to its cost,) is that you can have an entire graph of objects that are persisted to

    • Re: (Score:3, Insightful)

      Well, I'm currently working on a project that uses Hibernate in Java, and it's really quite hideous. I speak as someone who designed an object-relational mapping system ten years ago. Hibernate is much more powerful than anything I ever hoped to do - and it still sucks. We're talking about an application with 2 core classes, with a one-to-many relationship. Three tables in the underlying database. So it's about as simple a data model as you can get.

      To get it to perform, we're having to manually add inde

      • by mrtom852 (754157)

        It seems that more people are starting to realize the problems you've mentioned. I have always been amazed that practically every feature I could ever want is in Hibernate but at the end of the day knowledge that would have been gained about the underlying database is just replaced with Hibernate trivia.

        The two things that always amaze across projects is how little people understand hibernate's Session (sometimes not at all!) and how people fall in to the trap of creating huge object graphs. Developers ofte

    • by scorp1us (235526)

      I am using NHibernate for the first time.

      I wrote a layer like this by myself about 10 years ago for PHP. I gave up on it because I found it shallow and pedantic. If you have a developer that can't write a SQL query, then you need to look at your hiring practices or get some training. A basic technology like SQL is now 38 years old. It's not a secret.

      What's more the HQL is so similar to SQL as to not make a damn bit of difference. So what do you get? POCO mappings. The object management is handy, but really

      • by ZFox (860519)
        Have you looked at FluentNHibernate [fluentnhibernate.org]? It does away with the xml mapping files and strongly types everything (although it does this using lambda expressions, so expect a .net 3.5 requirement).

        I've been pleased with it and have been able to perform some pretty complex mappings to legacy databases with it (but you have the option to fall back to hml if things get real complex).
    • Re: (Score:3, Informative)

      by WarwickRyan (780794)

      What the ORM gives you (in addition to the obvious) is the power to make large scale changes to your persistance infrastructure quickly and easily.

      Take caching as an example. Every time you touch the database, you pay a relatively high cost. If the data you're accessing doesn't have complex sorting or querying, then you can dramatically improve performance by caching in the webserver's memory. If your db is on the network, then the cost is even higher. Guess what? With an ORM such as nHibernate, you ca

    • Re: (Score:3, Insightful)

      by Tablizer (95088)

      The root of the problem was that the engineers who started the project didn't know anything about database programming and just used NHibernate as a magic persistance layer.

      There is a growing consensus in the industry that OOP is not well-suited at direct modeling of domain (business) objects, such as employees, products, invoices, etc. I believe this is partly because OOP lacks inherent collection-oriented idioms, and would otherwise reinvent the database if it did. Further, heavy collection-orientation t

    • Re: (Score:1, Insightful)

      by Anonymous Coward

      You can't assume that one abstraction means you can ignore all others. If you use NHibernate you should already know about database programming and basic ADO. You don't get a free pass on the subjects when working with relational databases. Assuming NHibernate is going to be a golden ticket that means you get to ignore all ideas around a RDBMS is ridiculous. I have found that personally using NHibernate greatly reduces the amount of code I have to write and maintain and reduces the complexity of that code (

    • by randallman (605329) on Wednesday November 17, 2010 @06:00PM (#34261342)

      My experience has been similar to yours. I agree with you about the issues that exist, though I don't agree with your prescription to use only the basic features. ORM can drastically reduce code complexity and still perform well if you are willing to properly learn how to use the library and understand performance trade-offs. The main problem is that most people aren't willing to put in the time and effort (as with most everything in life).

      Some tips.

      • Make sure you have a good database design to begin with.
      • Turn on logging so that you can see the SQL statements issued. Are you pulling every field from a table when all you need is one? Are you selecting from related tables that aren't needed. Not everything need be done is the most efficient manner, but consider where optimizations can and should be performed.
      • Automated tests. Test your data model to make sure it performs both properly and efficiently.

      When using ORM, you have do have to pay attention to what's happening underneath. It's a trade-off, but in the end your code is much more simple and portable. After spending time with an ORM, surprise, you learn how to use it better.

    • Re: (Score:1, Insightful)

      by Anonymous Coward

      This is a classic case of a workman blaming his tools. Often, beginners start using NHibernate without fully understanding how it works and how to manage it (for example, if you're wrapping NHibernate around a repository pattern, you're doing it wrong and *will* eventually get burnt). And you're right, you do need to know the underlying database programming concepts; thinking you can ignore this even with the most powerful ORM is wishful thinking.

      Make sure you use the right tool/patterns - NHibernate Pro

    • Re: (Score:3, Informative)

      by mugnyte (203225)

      Parent sounds a little like they were in over their head. Was the problem NHibernate (the implementation) or the ORM (the concept)?

      As someone who's written an ORM that handled a medium swatch of the features for the product space (metadata, state, caching, lazy-loading, transactions mgmt, SQL generation, etc). I can say that done well, ORMs greatly simplify database-backed systems for any system size over ~10 tables, or systems with less-than-solid feature requirements.

      Simply put,

      • by GWBasic (900357)

        Parent sounds a little like they were in over their head. Was the problem NHibernate (the implementation) or the ORM (the concept)?

        Both.

        The problem was rooted in the fact that the engineers who started and lead the project had no clue how to program with a relational database, and treated NHibernate as a magic persistance layer. They would just quote the mantra of "Like Inversion Of Control, Test Driven Design, Policy Injection, Design By Contract" and then totally misunderstand how to act on the concepts.

        IE, they would do things like foreach over an entire table instead of "select where parentid=123". They would also suck an entire da

        • Re: (Score:3, Insightful)

          by mugnyte (203225)

          We were discussing this just today in the office. ORMs can suffer from huge impedance issues if not used correctly: Too chatty/lazy/narrow or too wide/wasteful.

          Overall, they're trying to pick a middle ground between writing plumbing per-UI need and having a one-size-fits-none model inflator. There's a lot of tricks in there (caching, lazy loading, dynamic objects, etc) but overall it's the same trade-off any system faces.

          There shouldn't be mountains of C# to wade through to get da

          • by GWBasic (900357)

            There shouldn't be mountains of C# to wade through to get data. If so, the implementation is off. The concept, however, I a big fan of. Even when the impedance is high.

            Which gets down to the root problem: The developers wrote a mountain of useless C#. ORM really wasn't an appropriate tool for the project, because it just didn't need all of the things that you use ORM for. All that was needed was a simple layer to map ADO results to objects, or even better, a document database.

        • by Skal Tura (595728)

          Sounds to me like you are describing the average coder in general, not just on this instance they were idiots :D

          Also, can basic CRUD be made much simpler than it is, it's BASIC crud afterall :)

          The most successfull DB work i've done was where 2/3 of the team were highly skilled DB admins. We did multiple very heavy data driven web applications, and got the insanely high amounts of data being handled really fast, but we did not use ANY stored procedures. Simply not seeing the value of a stored procedure makin

    • They do. I've been struggling with commercial and free ones since C++ was the hottest environment around and they all basically do the same thing: spit out useless code that is impossible to optimise on a large database. You can't tune it reliably, you end up with indexes out the kazoo all over your database trying to catch all the special cases that the damn OR mapper makes up and they all have truly, ugly, broken interfaces to anything a normal database programmer uses like stored procedures.

      I wrote on

      • by Skal Tura (595728)

        I have pretty much the same experience about ORMs, tho my experience is far more limited.

        But i somehow doubt it was just coincidence that the worst coder i've seen in my life is also the only coder i've seen using any ORM :)

        My belief is that ORM is for newbs who cannot comprehend the data structures/query language, or both. Resulting in doubly evil end results. But yeah, it seems to be that for the most part it's insanely hard for people to make simple efficient code with sane abstraction levels, and not ab

    • by cromar (1103585)
      Almost everything you say seems to be a misunderstanding of the best features of NHibernate.

      These guys would write foreach loops that would suck most of the database into RAM.

      NHibernate provides modular caching, so this is what you want. Generally, the data in the database is used by the application, so the more that is in memory the better.

      I found that it just makes data access more complicated

      It is perhaps the only library that allows true OO for database driven apps in .NET You may think it is "more complicated" than the ad-hoc data widgets provided by Microsoft, but those are tools ill fitted for any serious application. The benefi

    • I can't believe this screed got a +5 Informative. Your argument makes no sense.

      The root of the problem was that the engineers who started the project didn't know anything about database programming and just used NHibernate as a magic persistance layer.

      Really? They didn't know anything about database programming? First off: what does database programming have to do with .NET/Java programming? Second: how does someone who doesn't know anything about database programming go about creating libraries that do

  • by PJ6 (1151747)

    and it does so in an efficient, non-intrusive, and flexible manner

    Bwahahahaha!!!

  • NHibernate's implementation might be fine for Java but sucks for Desktop applications. Instead of paying the cost of parsing the object mapping files once (when the web server is started) you pay for it every time you start your application. It also guarantees that your efficiency is awful because of the way it's designed. Do yourself a favor and use something else.
  • by Skal Tura (595728)

    ORM is anything but efficient.

    Also, my experience of ORM so far it is for Newbs who cannot comprehend the data structures by themselves, making it doubly inefficient.

    Well, maybe one day i'll see a good example where it actually is efficient and powerfull :)

    • my experience of ORM so far it is for Newbs who cannot comprehend the data structures by themselves

      It's obvious you don't know what you're talking about. Data structures have nothing to do with ORM.

  • Thank god for all the bitching scripting "programmers" that despise ORMs and would rather use hand-written SQL statements. You keep the rest of us happily, steadily employed.

Man is the best computer we can put aboard a spacecraft ... and the only one that can be mass produced with unskilled labor. -- Wernher von Braun

Working...