Slashdot is powered by your submissions, so send in your scoop

 



Forgot your password?
typodupeerror
×
Books Media Programming Book Reviews Technology

Hibernate in Action 220

Adrian Spinei writes "From a documentation point of view, Hibernate is one of the most notable exception in the world of LGPL'ed projects. Its website offers a plethora of information, from solid documentation (the reference has no less than 141 pages) and various FAQs to sample projects and third-party resources. The forum is quite active and you may get answers to tricky questions. Or a little bit of rough treatment in case you haven't RTFM - but that is understandable, given the number of questions that the authors have to answer every day. Under these circumstances, one might wonder what Gavin King (Hibernate founder) and Christian Bauer (documentation/website maintainer and Hibernate core developer) can add in order to be able to write a 400-pages book about Hibernate. I mean - sure - only by joining the reference documentation, different FAQs and guides, one can easily 'extract' a hefty 'manuscript' with more than 200 pages." Read on for Spinei's review of Hibernate in Action.
Hibernate in Action
author Christian Bauer and Gavin King
pages 400
publisher Manning
rating unavoidable
reviewer Adrian Spinei
ISBN 193239415X
summary ORM pour les connaisseurs

Well, I am glad to tell you that this is not just a dump of the on-line docs. The book not only gets you up to speed with Hibernate and its features (which the documentation does quite well). It also introduces you to the right way of developing and tuning an industrial-quality Hibernate application. I consider myself a pretty seasoned Hibernate developer, being familiar with the API since its 1.2 version in Q1-2002 (if I remember well the first app when we used Hibernate). However, I was proved wrong by Hibernate in Action, which describes best practices and even API features that were unknown or vaguely known to me. That is, until now.

The first chapter, in the good tradition of all first chapters in the world, is an introduction. It's a very well written introduction about why do we need ORM solutions in OO applications. The chapter explains the O/R impedance mismatch, while declaring quickly that OODB sucks (immature and not widely adopted). Wel'll also find out that EJB also sucks from a persistence point of view (for various reasons). Which can be quite a surprise knowing that Gavin is one of the authors of EJB3.0 specs. Or, on the contrary, this will explain a lot of things in the new EJB specs.

Now that we have cleared the "why Hibernate" issue, let's continue to the second chapter. Which - tradition obliged - is a "Hello, world" and a "Let's get started" chapter. Here you go: almost 50 pages later you should be able to write simple Hibernate-based persistence layers and integrate within an application server, like for instance ... Jboss ! Humm, well, why not ? They are sponsors of the Hibernate project, after all.

In the 3rd chapter, our fresh knowledge will be put to good use by starting the development of an online auction application called CaveatEmptor. This app will follow our reading progression and will grow bigger and smarter chapter by chapter. But for the moment, we are at the inception phase. What gives: a little bit of analysis, a stylish class diagram of the domain model and the resulting mapping file. And if you thought (based on 2nd chapter) that the mapping file is very intuitive and simple, you're in for a big surprise -- it is, indeed, intuitive and simple! Quite bizarre for an open-source project. As a matter of fact, the mapping file is one of the pivotal elements of Hibernate, since it addresses directly the O/R impedance mismatch, a recipe for transparent linking your POJOs and the constrained relational model. No wonder that a big part of this chapter is aimed at explaining why and how the mapping works in Hibernate. You'll see how class associations and inheritance translate at the metadata and mapping level. You'll start to understand the things that you took for granted in the previous chapter and you'll have that pleasant "uuh, I see" chain reaction. Hold on, it's just the beginning.

Because chapter 4 is going to explain once and for all the lifecycle of persistent object in Hibernate, their behavior from a persistence point of view as well as the available fetching strategies. And if you thought you already knew everything by heart from the documentation ... well, maybe you do know everything by heart. Nevertheless, it's very well synthesized in chapter 4 and I'll recommend it anytime to a coworker eager for Hibernate knowledge.

In the next chapter (the 5th) the rollercoaster slows down a bit. That is, if you already know the behavior associated with the four possible isolation modes in transactions, what are the different types of locking, what (the hell) MVCC means and the importance of transaction scopes. Chances are you already know some of this stuff quite well, but everybody needs a refresher from time to time, especially when it's well explained and when it comes with versioning and caching (1st and 2nd level) in Hibernate as a desert. By the way, I thought that OSCache supports clustering, not only SwarmCache and JbossCache, as stated in the book. There's even a thoroughly explained example of using JbossCache as a level 2 clustered cache for Hibernate, but it shouldn't be too hard to convert to other types of caching systems.

Now, if I were the author of the book, I would have placed chapter 6 before chapter 5. But I am not the author, which is quite fortunate for you dear readers since Christian and Gavin are much more competent than me at writing books about Hibernate (and probably at some other unrelated domains). They have decided to go back to mapping in chapter 6, after the short transaction/caching intermezzo. Well, they should know better... it's time for a serious dose of advanced mapping. This chapter is attacking interesting subjects such as custom mapping types (simple or composite) and (finally) the mapping of collections. Special guests stars: the whole gang of "sets, bags, lists and maps", together with explanations about their relational equivalent (associations, associations and associations !). Oh and yes "polymorphic association" (section 6.4.3) - I wasn't even aware that Hibernate is able to do that... guess I'm not that 'seasoned' (as a Hibernate developer) after all.

The 7th chapter is about "Retrieving objects efficiently" : about 45 pages for the 'retrieving' part and 6 pages for the 'efficiently' part. Fair enough ! You'll learn how to master basic HQL queries (parameters, pagination ...). You'll get a grip on the query by criteria API, as well as on advanced stuff such as dynamic queries, filters, subqueries and native SQL (very powerful). At the end of the chapter there's the Hibernate-specific solution for the n+1 selects problem, query caching and result iterators.

Following this wealth of useful knowledge, the 8th chapter starts a bit dry. Nevertheless, after a short introduction about Hibernate in managed environments, you'll find yourself again in the land of advanced programming techniques : application-level transaction implementation ! This is mostly new stuff (at least for me) - a great collection of best practices for transactional behavior management in industrial-quality apps. Somewhat unrelated but still interesting, the chapter ends with legacy schemas integration and a smart implementation example for audit logging.

The 9th (and last) chapter is about the round-trip development in Hibernate using the classical toolset : Middlegen and/or hbm2java and/or XDoclet. All the available techniques are presented in a very detailed, step-by-step manner.

Wait : don't close the book, there's more ! Ignore Appendix A (a short and rather uninteresting document about SQL fundamentals - that is, if you know SQL). Appendix B contains mildly un-fascinating ORM implementation strategies pour les connoisseurs (come on guys, I'm just a dumb user). But - Appendix C is a great collection of real-world stories and by all means read them all ! Especially the last one, a treasure of hard to find knowledge (no spoilers, please...).

In the end, I have to confess that there is something truly interesting about Hibernate In Action : albeit very technical, it reads astonishingly easy - and this kind of books is unfortunately very rare nowadays. My congratulations to the authors for this excellent piece of work - it was worth the wait.

As for you dear potential reader, if you already know all the information detailed in the book, I bow before you, great Hibernate wizard.


You can purchase Hibernate in Action from bn.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.

Hibernate in Action

Comments Filter:
  • by MarkWatson ( 189759 ) on Monday October 11, 2004 @02:08PM (#10495315) Homepage
    Hibernate is a very solid Java object relational mapping tool (I have a section on Hibernate in my last book). When you need OO to relational database mappings, Hibernate is my recommended tool, for sure.

    However, for my Java consulting business, Prevalyer [prevayler.org] is definitely my new "secret weapon". With a little care, it is easy to set up your POJO classes so that you can add class attributes without breaking your persistent Prevayler object store. Using Prevayler reduces development time. Good stuff.

  • by Palshife ( 60519 ) on Monday October 11, 2004 @02:09PM (#10495326) Homepage
    I really wish the story submitter would have taken a moment and put a one or two sentence explanation of what Hibernate is. It's not exactly a descriptive name, which I'll concede is common in our industry.

    Hibernate is an API for Java that uses Java Beans (get() and set() methods for all properties) to create, read, update and delete rows from a database. It's really cool. It's sometimes called JDO (Java Data Objects) but it's a dangerous association because of the Sun Reference Implementation of JDO, which is its own specification. Hibernate is different.
  • by Jouser ( 243992 ) on Monday October 11, 2004 @02:10PM (#10495347) Homepage
    From hibernate.org through google's cache:

    Working with object-oriented software and a relational database can be cumbersome and time consuming in today's enterprise environments. Hibernate is an object/relational mapping solution for Java environments. The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.

    Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

    Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate adapts to your development process, no matter if you start with a design from scratch or work with a legacy database. Hibernate generates SQL for you, relieves you from manual result set handling and object conversion and keeps your application portable to all SQL databases. Hibernate provides transparent persistence, the only requirement for a persistent class is a no-argument constructor. See our list of frequently asked questions about Hibernate.

    Hibernate is typically used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans. See this page for an overview of Hibernate application architecture.
  • by jonathanduty ( 541508 ) on Monday October 11, 2004 @02:11PM (#10495366) Homepage
    Hibernate is a Java persistance layer. Basically, you can map java objects to a database schema (doesn't matter which one comes first). If I have a table called "user", I can create a java class called "user" (or whatever I want to name it) and use that class to access the database, without writing any sql. I've used a few different persistance frameworks and Hibernate is at the top of the game for now. If you are writing a java app that will access a database I highly suggest you take a look at it. Pure JDBC still has its place in the world, but Hibernate tends to make life a lot easer (and less messy).
  • by grunt107 ( 739510 ) on Monday October 11, 2004 @02:12PM (#10495376)
    Hibernate is purported to be a persitent object programming tool.

    This was grabbed off www.onjava.com:
    Hibernate will help us to painlessly store the data in permanent storage without too much hassle about choosing the kind of storage, installation, or configuration. Hibernate allows us to store any kind of objects; therefore, our application does not need to know that its data will be persisted using Hibernate. Of course, everything mentioned here can be applied in the opposite direction: fetching already prepared objects from a storage is now nearly trivial. Updating and deleting data is also available.

    Judging by their inaccessible website, Hibernate is what they do best.
  • Re:So what is it? (Score:3, Informative)

    by DA_MAN_DA_MYTH ( 182037 ) on Monday October 11, 2004 @02:21PM (#10495472) Homepage Journal
    It's a object relational persistence Manager for Java, kinda like JDO. Nifty little tool so you don't have to make your own persistence calls with JDBC, saves a lot of keystrokes. I bought the book and it shows a lot of different tricks, and with Hibernate's QBE (Query By Example), saves a ton of time debugging dynamic SQL Calls.

    I've been using this for quite a while, coupled with Spring [springframework.org] you can write a lot of robust reusuable objects, if you utilize java's OO design methods.
  • Re:Hibernate? (Score:3, Informative)

    by easter1916 ( 452058 ) on Monday October 11, 2004 @02:30PM (#10495559) Homepage
    Hibernate is a persistence layer for POJOs (plain old Java objects). Basically a way to map objects to an RDBMS, and manage transactional persistence. See http://www.hibernate.org/ [hibernate.org] for more information.
  • by MarkWatson ( 189759 ) on Monday October 11, 2004 @02:34PM (#10495597) Homepage
    I sometimes do the same thing myself (i.e., just write a little code using the JDBC APIs to grab what I need).

    Also: with Hibernate, you do have control over how much of a row of data you actually retrieve since you specify the mapping that you want in an XML configuration file.

    Do try Prevayler however: for some applications it really is a great tool. I especially like it for web applications where most data access is read only: caching objects in memory really speeds things up.
  • by teutonic_leech ( 596265 ) on Monday October 11, 2004 @02:34PM (#10495598)
    I have used Hibernate on the last two J2EE projects I've worked on and can attest to its simplicity and power. Although it'll take you a few weeks to really get the hang of how things work under the hood, it's well worth the learning curve. And it's ridiculously simple compared with EJB - that's for sure. My latest project even involved storing CLOBs to an Oracle Rack cluser - it took a bit of tweaking and research, but we saved ourselves hundreds of lines of codes and it performs without a glitch.
    Okay, I haven't RTFA, but the poster should also have made mention of Spring, which works hand in hand with Hibernate. Spring basically is an Inversion Of Control (IOC) framework, that allows you to define Hibernate transaction and session contexts. Spring also offers a great MVC layer, but one does not have to use that. If one chooses to just use Spring as an addition to Hibernate, one can look at Spring's additional functionalities as needed. Spring also offers Oracle BLOB/CLOB support by offering a customized OracleClobHandler - Oracle ONLY supports its propietary CLOB objects and won't accept java.sql.Clob objects via Hibernate.
    Generally, Hibernate is very non-intrusive and gives you the opportunity to write JDBC code alongside with your Hibernate code (which is super-elegant and abstracted the way it should have been done a long time ago). So, it can be slowly folced into an existing project without having to refactor any legacy code.
    The Hibernate user group is a bit rude to be quite frank - I've tried to post some questions in the dev group and got pretty angry replies. The 'beginner' group was not very helpful, so I had to google for answers. Of course there's the book, and I would strongly recommend to get it, since it is one of the major revenue sources for those Hibernate contributors. We want open source, but we can't expect to get everything for free, right? ;-)
    My first exposure to Hibernate was through the Appfuse framework [raibledesigns.com], which is an excellent J2EE kickstart project, complete with ant built, Xdoclet, Hibernate, Spring, the works. I was even able to use XDoclet tags inside my Java beans, relieving me of having to write my Hibernate definition files by hand! It really doesn't get much easier than that. For anyone wanting to give Hibernate/Spring a try, I recommend to download the latest version of appfuse and give it a try - it's a liberating experience. The biggest kick I got was being able to seamlessly switch my project from Oracle over to MySQL by simply changing a few environment variables - I mean, how cooler can it get? :-)
  • by Tailhook ( 98486 ) on Monday October 11, 2004 @02:41PM (#10495681)
    (doesn't matter which one comes first)

    Actually, it does matter which comes first. Hibernate works best (best defined as most clean, simply) if you have the luxury of a well normalized schema where every table contains a surrogate key. Obviously, if you're working from a clean sheet this is an worthy design choice, relatively easy to satisfy.

    However, if you are working with a pre-existing design and you can't retrofit surrogate keys, you're in for a lot of additional leg-work with Hibernate. Getting Hibernate to function with composite keys forces extra coding and imposes limitations. This was my experience 9 months ago when I had a look at Hibernate for an "enterprise" application that must work with vendor schemas.

    I don't fault Hibernate; persistence is hard. Mapping an object from RAM to relational storage is much easier when you have a simple 1-to-1 relationship between objects and integers. Working well only with simple surrogate keys is not unique to Hibernate by any means. In principle you're correct; it doesn't matter which comes first. In practice, if you're dealing with composite keys or any form of denormalization you're in for a lot of pain.
  • by rycamor ( 194164 ) on Monday October 11, 2004 @02:51PM (#10495806)
    Notice this quote [javaperfor...tuning.com] by one of the Hibernate developers in an interview earlier this year:

    "I went into this knowing very little about ORM, and even very little about databases. One of my first tasks was to go out and buy a book to learn SQL properly. All my understanding of the problem comes from what our users have taught us over the last two years."

    Sigh... basing a product on secondhand experience from users who probably have never even learned what the relational model is really about.
  • by rudedog ( 7339 ) <{dave} {at} {rudedog.org}> on Monday October 11, 2004 @02:55PM (#10495858) Homepage
    So many initial posts asking what Hibernate is when it is probably the poster child of Java Open Source (OK JBoss might be better known but unlike JBoss Hibernate is universally well regarded). Disappointing really.

    It sounds like this may come as a complete surprise to you, but not everybody is a Java programmer. Why should non-Java programmers be expected to know about a Java-only tool?
  • Hibernate (Score:1, Informative)

    by Anonymous Coward on Monday October 11, 2004 @02:59PM (#10495892)
    I program in both Java and .Net. For those people who wants to use hibernate with .net has a port of hibernate called Nhibernate.
  • by JASegler ( 2913 ) <jasegler@@@gmail...com> on Monday October 11, 2004 @03:46PM (#10496387)
    I've had the misfortune to inherit a project that was written by someone who believed Hibernate is a persistence layer.

    Hibernate is tempermental at best and broken at worst. The biggest problem is it has it's own special language called HSQL which gets converted into SQL at runtime.

    HSQL is supposed to be database neutral. However, things don't work the way they are supposed to all the time. Specifically CLOB/BLOBs on DB2 for OS390 crash the OS390 JVM. Other things fail (sometimes silently) in unexpected ways. I suspect alot of the problems I have with hibernate are due to the fact that it's hard for most people to access a JVM running on OS/390 talking to DB2 on OS/390. Because of that hibernate apparently has little/no testing against that environment.

    Hibernate has more features than JDBC but in the end you still have to build out your real persistence layer code to handle all the parent<->child relationship things in your object hierarchies.

    I already have programs that will take a database schema and create the domain, broker and standard SQL statements for JDBC based persistence layers. Hibernate doesn't save any development time for me. And anyone else that has been doing java for a few years probably has the same sort of tools and it won't save them any time either.

    However, if you were starting from scratch, in an environment heavily supported by Hibernate it probably would not be a bad choice to go with.
    Just don't think it will magically do all the hard things like tracking updated/deleted/new objects, cascading auto generated keys from parent to child (or child to parent if your tables swing that way) or sequence delete/update/inserts to avoid referential integrity problems.

    -Jerry
  • by Anonymous Coward on Monday October 11, 2004 @03:51PM (#10496446)
    You may want to look at Cayenne. It handles mapping legacy databases much better than Hibernate, as it supports flattening one-to-one and many-to-one relationships, and also has a GUI for reading pre-existing DB metadata and subsequently configuring/generating your object structure. I used it to map an old, clunky Oracle 7 database to a nice, logical object hierarchy and it made everyone's life easier.
  • by easter1916 ( 452058 ) on Monday October 11, 2004 @04:56PM (#10497037) Homepage
    • ORM = Object-Relational Mapping, that is, a framework for persisting objects to a relational database.
    • O/R Impedance = The problems and technical difficulties associated with Object Relational mapping.
    • OODB = Object-Oriented Database, as opposed to an RDBMS (Relational Database Management System), i.e., a database that supports objects natively.
    • EJB = Enterprise Javabeans (see java.sun.com for an explanation of these monstrosities).

    I hope that helped.
  • by teutonic_leech ( 596265 ) on Monday October 11, 2004 @06:09PM (#10497690)
    Not true. It took me a LOT more time learnng how to write good JDBC code, that didn't break in an enterprise enviornment. Had I had access to Hibernate back then, my life would have been infinitely easier. Finally, Gavin actually offered a cash price for anyone writing manual JDBC code which would be faster than Hibernate - so far nobody has come to collect it.
  • by slashddot ( 821093 ) on Monday October 11, 2004 @06:29PM (#10497862)
    Actually, compositite keys have been supported by Hibernate beginning with version 2.0, which came out over a year ago. See here [hibernate.org].

    Usually, problems with mapping existing database schemas to Hibernate arise from the shorcomings of the database and not Hibernate. Oracle's CLOBs and BLOBs are a good example of this, as the methods exposed by the JDBC interface do not work properly and methods from Oracle's CLOB and BLOB classes must be used directly, breaking transparency and forcing the developer to do additional work.

    i.

One way to make your old car run better is to look up the price of a new model.

Working...