Hibernate Performance Tips

Discussions

News: Hibernate Performance Tips

  1. Hibernate Performance Tips (77 messages)

    Jason Carreira has written up some of his own Hibernate performance tips. He discusses key generation, lazy loading, caching, and jumping on Hibernate3. What are the gems that you have found?

    Read more: Hibernate Performance Tips

    Threaded Messages (77)

  2. Hibernate Performance Tips[ Go to top ]

    For now, it appears jroller has been hijacked.
  3. Hibernate Performance Tips[ Go to top ]

    One thing that would make things faster is to make sure you index columns of your tables that you perform lookups on (aside from the primary key). I haven't found a setting in Hibernate that would do this for me. Or at least do it so that the combination of two columns have to be unique.
  4. Hibernate Performance Tips[ Go to top ]

    One thing that would make things faster is to make sure you index columns of your tables that you perform lookups on (aside from the primary key). I haven't found a setting in Hibernate that would do this for me. Or at least do it so that the combination of two columns have to be unique.

    You can add the index element to you hibernate mapping, and if you have updateSchema, then hibernate will create that index for you. You can cache the results for queries too. I often do that for common lookups on non PK unique fields.
    Query q = new Query("from Foo f where f.bar=?");
    q.setParameter(0, value);
    q.setCacheable(true);
    return q.uniqueResult();
  5. Good info[ Go to top ]

    Next time someone tells you they heard Hibernate is slow start asking them about how they configured caching, lazy loading, etc.
  6. Hibernate Performance Tips[ Go to top ]

    I bought Hibernate in Action by Christian Bauer and Gavin King. It is an excellent book full of gems about Hibernate use and ORM in general.
  7. Hibernate Performance Tips[ Go to top ]

    I bought Hibernate in Action by Christian Bauer and Gavin King. It is an excellent book full of gems about Hibernate use and ORM in general.
    I agree. A really good book (as well as many other books from Manning).
    If you like it, you can also vote for it in the Sys-Con Media's 2005 Readers' Choice Awards : http://sys-con.com/java/readerschoice2004/liveupdate.cfm?BType=1
  8. Hibernate Performance Tips - lazy loading[ Go to top ]

    i don't see how to easily use lazy loading and maintain a good design. with lazy-loading, any resolution of a lazily-loaded reference has to be accomplished in the same hibernate session. so you cannot have a data access layer give back any lazily-loaded objects unless the lazy references are guaranteed to not be referenced in the business layer or the business layer manages the hibernate session. the former is cumbersome (in that i have to have my data layer build all sorts of permutations of objects and their kids) and the latter means that the business layer has to know that the data access layer is implemented in hibernate.

      because of this, i actually am not using lazy-loading but storing IDs in objects where i don't want to build the children.

      i'd welcome an explanation of a better way to do this.
  9. ...the business layer has to know that the data access layer is implemented in hibernate...
    The typical solution (for the web applications at least) is to introduce a Filter that would manage a Hibernate session "before" and "after" every hit. Then the Hibernate knowledge would only be contained in such Filter.
  10. I'm just starting hibernate (actually performing major overkill since the app I am building only has one table).

    The site just brings us to tips, but I am wondering if there is a best practices document? For example
    Define your Session management strategy early.
    What would the best session management strategy be? I guess some of it would be answered in the Hibernate In Action book I hope, I am still scanning through it at this moment.
  11. I'm just starting hibernate (actually performing major overkill since the app I am building only has one table).
    At least you won't have any lazy initialization issues. :)
    The site just brings us to tips, but I am wondering if there is a best practices document? For example
    Define your Session management strategy early.
    What would the best session management strategy be? I guess some of it would be answered in the Hibernate In Action book I hope, I am still scanning through it at this moment.
    Yes. See the book and the corresponding code (downloadable). Wish I had looked the project code before I started my latest project.
  12. Hibernate is never overkill, it's simple to use , reduces
    the amount of code you need to write and saves you from writing
    a line of sql. if you can use it you should use it.
  13. ...the business layer has to know that the data access layer is implemented in hibernate...
    The typical solution (for the web applications at least) is to introduce a Filter that would manage a Hibernate session "before" and "after" every hit. Then the Hibernate knowledge would only be contained in such Filter.

    i've seen this, and i expect it works fine. but now you're managing your data access layer in your presentation layer, which is even weirder from a design standpoint, i think.
  14. i've seen this, and i expect it works fine. but now you're managing your data access layer in your presentation layer, which is even weirder from a design standpoint, i think.
    I am wary of layer separation strategies that come at the cost of simplicity (ie, many designs with DTO). The SessionFilter (for web apps) simply knows when a request starts and finishes, and handles the Session for all layers accordingly. I would not say it resides in the presentation layer, rather that it integrates the layers, who still need know nothing about each other's implementation. I believe there is a general movement towards this interceptor/IOC approach, as opposed to cauterizing the interface between layers. You still get the session management code in one place, only it is no longer "in" the database layer. Many find it to be more manageable.
  15. i've seen this, and i expect it works fine. but now you're managing your data access layer in your presentation layer, which is even weirder from a design standpoint, i think.
    I am wary of layer separation strategies that come at the cost of simplicity (ie, many designs with DTO). The SessionFilter (for web apps) simply knows when a request starts and finishes, and handles the Session for all layers accordingly. I would not say it resides in the presentation layer, rather that it integrates the layers, who still need know nothing about each other's implementation. I believe there is a general movement towards this interceptor/IOC approach, as opposed to cauterizing the interface between layers. You still get the session management code in one place, only it is no longer "in" the database layer. Many find it to be more manageable.

    to me, this is a very compelling argument. thanks.
  16. |
    |but now you're managing your data access layer in your
    |presentation layer, which is even weirder from a design
    |standpoint, i think
    |

    See comment above re storing Session in ThreadLocal.

    While strictly speaking, it is in your presentation "layer", in reality your presentation layer code should know nothing about it. ThreadLocal does that.

    In reality, even though we think of transactionality, etc as being a data access layer-enforced issue - most of the time, the transaction semantics (isolation, locking strategy) are specific to the user action. More of these semantics are lost the further away from the presentation layer you go...

    In any case, think of the filter as an "aspect"...

    -Nick
  17. i don't see how to easily use lazy loading and maintain a good design .... means that the business layer has to know that the data access layer is implemented in hibernate.  because of this, i actually am not using lazy-loading but storing IDs in objects where i don't want to build the children.  i'd welcome an explanation of a better way to do this.

    Sure thing. You don't expose Hibernate objects in and of themselves. Wrap them up in a Transaction interface, or some such thing, and pass that down. That way your business code knows it's transacted (isn't that a good thing?) and your persistence layer knows that since it produced the transactions, it can downcast to HibernateTransactionImpl or whatever and fetch out the session.
  18. i don't see how to easily use lazy loading and maintain a good design. with lazy-loading, any resolution of a lazily-loaded reference has to be accomplished in the same hibernate session. so you cannot have a data access layer give back any lazily-loaded objects unless the lazy references are guaranteed to not be referenced in the business layer or the business layer manages the hibernate session.
    That is no problem at all, the only thing is to maintain the Hibernate session through your application "transaction" logic. There are two useful patterns in this regard: Hibernate-session-per-HTTP-request and Hibernate-session-per-application-transaction.

    I believe Spring has an implementation, at least, for the first one.

    What happens is that - you do not open a new hibernate session for each operation but your framework opens it at the begining of the HTTP request (or application transaction that can span through several HTTP requests) and domain objects grab it from there. Framework is also responsible for closing/flushing session at the end.

    If you use one of those patterns (and I highly advice to take a look at Spring's implementation ) - you will not have problems, with the lazy loading that you mention. Your code will be much cleaner and way better performing. Lazy loading _really_ makes huge difference.
  19. Take a look at the Spring framework. Even if you don't use it in your projects, you can see how they tackle this issue.

    For Web applications, see OpenSessionInView and OpenSessionInViewFilter (in the Spring framework). For other applications, see SessionFactoryUtils and HibernateInterceptor.

    The basic approach is: bind the Hibernate session to a ThreadLocal (assuming a unit of work will be done in a single thread) and use it for the life of e.g. a web request which makes multiple DAO calls from the business layer.
  20. i don't see how to easily use lazy loading and maintain a good design. with lazy-loading, any resolution of a lazily-loaded reference has to be accomplished in the same hibernate session.

    Sorry but this is just plain wrong.
    Simply use Session.lock() method to re-join detached object to new session and voila.

    I've using that pattern successfully when Tapestry is used for the frontend: e.g. when one Tapestry page (OrderList) contains Collection of Orders with lazy-loaded lines, and when you want to drill-down, another page (OrderDetails) is instantiatied with attribute Order - and in attach() page method you just open new session and do .lock() for this order - and then happily lazy-load its lines!
  21. User Servlet Filters[ Go to top ]

    The way I'm implementing it now is by creating a servlet filter that closes the HibernateSession at the end of the request. I don't user any close session statement in the hibernate dao. This way I get one session per request and I don't get those pesky lazyinitialization errors.

    Marc
  22. hibernate 3 - one other point[ Go to top ]

    the author suggests using hibernate3, but if you are using spring and it's hibernate integration, you cannot do this, since the entire package structure changed. spring 1.2 will support hibernate 3, but i don't know when we'll see spring 1.2
  23. hibernate 3 - one other point[ Go to top ]

    the author suggests using hibernate3, but if you are using spring and it's hibernate integration, you cannot do this, since the entire package structure changed. spring 1.2 will support hibernate 3, but i don't know when we'll see spring 1.2

    If an API is fairly clean (the way Hibernate is), I don't see why Spring is needed anyway. I've used Spring for an RMI server/client, and it was perfect for that bcz its API and semantics were just awful. But, in Hibernate world, unless you are planning to use transactions, I don't see what benefits you receive from using Spring in conjunction with Hibernate. There are even negative effects like the one you've indicated, that Spring falling behind a major release of the APIs it wraps.
  24. hibernate 3 - one other point[ Go to top ]

    If an API is fairly clean (the way Hibernate is), I don't see why Spring is needed anyway

    I dont think anyone suggests Spring is needed with Hibernate - like some sort of crutch. As you say, Hibernate is very clean to begin with.

    The point is, that using IOC (which Spring gives you) makes your application easier to unit test - including your data access (hibernate) code.
    Also, the declarative transaction demarcation saves you a lot of code - and keeps that aspect hidden from your application code.
    There are even negative effects like the one you've indicated, that Spring falling behind a major release of the APIs it wraps

    Given that Spring will release with H3 support as soon as H3 is released - I wouldnt say that constituted "falling behind". AFAIK, H3 support exists in Spring src tree now, if people want to play with it...

    -Nick
  25. hibernate 3 - one other point[ Go to top ]

    The point is, that using IOC (which Spring gives you) makes your application easier to unit test - including your data access (hibernate) code.

    Er - Hibernate is POJO based, so it already IS easier to unit test. Plus, if there is no black magic done on the object that's being injected in the code, I see no point in using IoC, bcz I could simply "new" this object and use it.

    On the release cycles: It's good Spring release cycle is fast. But it's not instant. And that's natural. But for a team lead whose schedule falls in that time span trying to pick a technology, falling behind would be a crucial factor.

    So let me qualify my answer with more ifs; Unless an app uses transactions, has RMI or JNDI which have messy interfaces, it makes no sense to use Spring.
  26. hibernate 3 - one other point[ Go to top ]

    So let me qualify my answer with more ifs; Unless an app uses transactions, has RMI or JNDI which have messy interfaces, it makes no sense to use Spring.

    What about a consistent set of (unchecked - lot less coding) DataAccessExceptions?

    Martin Smith
  27. hibernate 3 - one other point[ Go to top ]

    What about a consistent set of (unchecked - lot less coding) DataAccessExceptions?Martin Smith

    That is good, don't get me wrong, but that alone does not suffice to add Spring on to a mix of, say, Struts + Hibernate which are already clean enough.

    Again, I am talking no RMI, no tx, no JNDI, etc.
  28. hibernate 3 - one other point[ Go to top ]

    That is good, don't get me wrong, but that alone does not suffice to add Spring on to a mix of, say, Struts + Hibernate which are already clean enough.
    Yes, that's clean enough. As well as JSP+Servlets+Javabeans can be very clean too. At least, until the requirements change or the application evolves to something that has an 'entreprise' taste. The advantage of Spring is not clean layered code, it's the ability to change the "shape" of an application quickly.
  29. Hibernate with Spring to me...[ Go to top ]

    is a slam dunk. Spring helps to manage and decouple my resources. Spring folds Hibernate's checked exceptions onto a common set of unchecked exceptions. Spring allows declarative services, and allows sharing common resources like the data source with other applications. I can switch between XA transactions and Hibernate transactions and JDBC transactions in configuration, without coding impact. In short, I write much less code to do the same amount of work.

    Spring/Hibernate integration is one of the best reasons to use either framework, in my opinion. For those who have never tried it, download Spring and check out the facade in the PetClinic application. Facade methods are one line of code each. That's not always the case, but it does show the reduction in handling overhead. It's a very powerful combination. And one of the downsides of JDO...integration is not quite as clean.
  30. hibernate 3 - one other point[ Go to top ]

    The advantage of Spring is not clean layered code, it's the ability to change the "shape" of an application quickly.

    Look, taking some Java code out, and putting XML files in its place doesn't qualify as "changing the shape application quickly". Clean maintainable enterprise code can be written in Struts + Hibernate environment without the use of Spring. But for RMI, JNDI, code, tx support, whose interfaces I would rather to keep out of my code, I would definitely use Spring.

    The simple rule of thumb is using the right tool for the job, isn't it?
  31. hibernate 3 - one other point[ Go to top ]

    Look, taking some Java code out, and putting XML files in its place doesn't qualify as "changing the shape application quickly".
    If you have a lot of "new SomeClass()" in your code, it can be difficult to change "SomeClass" into "SomeOtherClass". If you have just one XML (or a few XMLs) files where "SomeClass" is typed, it makes the work much easier.
    Clean maintainable enterprise code can be written in Struts + Hibernate environment without the use of Spring.
    I agree. And not only with Struts + Hibernate. But it needs more effort than when using Spring.
    The simple rule of thumb is using the right tool for the job, isn't it?
    Of course. That's also my motto.
  32. hibernate 3 - one other point[ Go to top ]

    Unchecked exceptions are my least favourite of aspect of Spring (I dont use it) - and will become my least favourite aspect of Hibernate 3...

    There is a reason why there are both types of exceptions in the JDK runtime.

    Unchecked exceptions should be used for errors of a fatal nature - you arent required to catch them because there is bugger-all you can do with them.
    Checked exceptions stand some chance of recovery.

    A DB connection failure isnt fatal. A SQL syntax error is.

    So rather than diffentiate between them, they are now all lumped together into the "guess what can come out of this method" category...

    -Nick
  33. You don't have to use Spring's IoC facilities if you'd rather handle service instantiation, configuration, and lookup yourself within your app (using custom factories, service locators, property files, and/or bootstrappers, whatever.) While I would not recommend this (as Spring's container is extremely powerful and full-featured), it certainly is an option you have.

    That said, Spring's data access module still provides substantial value in the case for Hibernate-based apps that don't need transactions or don't wish to be configured via Spring IoC. The Hibernate integration provides a template-based API that encapsulates hibernate resource, connection, and exception management into a developer-friendly API that is consistent and very easy to use. Bottom line, this approach greatly reduces lines of code, and eliminates bugs from inconsistent usage of the Hibernate API. It will improve the quality and maintainability of your data access layer, no doubt about it.

    Keith
  34. You don't have to use Spring's IoC facilities if you'd rather handle service instantiation, configuration, and lookup yourself within your app (using custom factories, service locators, property files, and/or bootstrappers, whatever.) While I would not recommend this (as Spring's container is extremely powerful and full-featured), it certainly is an option you have.That said, Spring's data access module still provides substantial value in the case for Hibernate-based apps that don't need transactions or don't wish to be configured via Spring IoC. The Hibernate integration provides a template-based API that encapsulates hibernate resource, connection, and exception management into a developer-friendly API that is consistent and very easy to use. Bottom line, this approach greatly reduces lines of code, and eliminates bugs from inconsistent usage of the Hibernate API. It will improve the quality and maintainability of your data access layer, no doubt about it.Keith

    Well said! Spring's factories alone are worth the price of admission. For example, when someone now asks object creation in our, code, instead of walking through our old custom factories or given them out of date documentation that I haven't (bothered to/wanted to/had time to) keep up to date, I hand them the Spring documenation. Here's all you need.

    The resulting code in one project that didn't need transaction support was as small(those one liners) as the code that in another that used transaction support.

    And guess what? It all looked ALIKE! I'm out of the Session management business and into get the work done quickly.
  35. hibernate 3 - one other point[ Go to top ]

    |
    |So let me qualify my answer with more ifs;
    |

    :-)

    |
    | Er - Hibernate is POJO based
    |
    I had noticed that ;-)

    I was referring less about your persistant objects - more about the wiring together the data access layer (the bit that does touch hibernate) to the rest of your application.

    Firstly, using an IOC design, you can easily detach your persistance layer for mocking.
    Secondly, using an IOC design (and avoiding direct usage of statics or singletons in your DAO) you can also unit test your hibernate code - make sure queries are assembled correctly, results handled correctly and more importantly, errors are handled correctly.
    Thirdly, by keeping the session management out of your code (handled by declartive tx demarcation), it also makes your code easier to test.

    (oh, and by the way, what app doesnt use transactions?)

    -Nick
  36. hibernate 3 - one other point[ Go to top ]

    You can get IOC without a container. See article Examining the validity of Inversion of Control.

    If you are using IOC correctly all your heavy stuff like Remote Services (via RMI or JAX-RPC), JNDI lookups, DataSource lookups, Transaction support, etc. should bubble up to the top where an EJB and EJB container can manage it. A HibernateSession would bubble up to the EJB as well. Managing these at this point is essentially having variables at the right scope i.e. member or local plus their init and destroy which can refactored for reuse application wide. Do you need another container to manage this?

    Spring would definitely be useful if you don't use or like an EJB container and want to obtain similar management facilities for the heavy stuff but I'm not sure if Spring has the deployment and administration facilities to manage these across an enterprise cluster.
  37. hibernate 3 - one other point[ Go to top ]

    p.s. Maybe Hibernate should throw Runtime DataAccessExceptions instead of generic HibernateExceptions that a caller cannot diagnose normally. Specific exceptions would still be checked e.g. StaleObject...
  38. hibernate 3 - one other point[ Go to top ]

    You can get IOC without a container. See article Examining the validity of Inversion of Control.
    If you believe in the validity of so-called "Context IoC". See the thread discussing that article for numerous convincing criticisms of the approach.
  39. hibernate 3 - one other point[ Go to top ]

    If an API is fairly clean (the way Hibernate is), I don't see why Spring is needed anyway.
    The IoC and dependency injection concepts that Spring brings in your code guarantee a clean separation of the interactions between the multiple components of your application. Therefore, switching from an infrastructure to another is made easier. One of the multiple advantages of this: you can run unit tests outside the application server (for example, from an ANT script that executes continuous builds).
  40. Spring and Hibernate3[ Go to top ]

    If an API is fairly clean (the way Hibernate is), I don't see why Spring is needed anyway.

    I assume you're talking about Spring's explicit Hibernate support. Of course, this is completely independent from Spring's core container: You can have a Spring-managed application that uses Hibernate3 directly, for example, instead of through Spring's Hibernate support.

    Essentially, you can use any APIs you want in components managed by Spring's core container. The pre-built support classes that we offer in the Spring download are only an option: Use them if they add value for your scenario; else let your application classes use native APIs.
    But, in Hibernate world, unless you are planning to use transactions, I don't see what benefits you receive from using Spring in conjunction with Hibernate.

    Well, "transactions" is a keyword here. The Hibernate guys themselves say that you should always execute your data access operations within transactions. Transactions are not some rare requirement; they are a necessity. This applies to EJB-based applications as well as to J2EE web applications running in Tomcat and to standalone business applications with a Swing GUI. Spring provides a consistent model here, both in J2EE and non-J2EE environments.

    So the main value that Spring's explicit Hibernate support adds is managing Hibernate Sessions within transactions: either one Session per transaction or one Session per HTTP request (Open Session in View). This still adds value on top of Hibernate3: Hibernate itself can only close opened Sessions at JTA completion there, but it won't give you a shared Session across multiple DAO calls within the same transaction, and it won't give you analogous support in a non-JTA environment (for example, in Tomcat).

    Additionally, Spring's DAO support also adds consistent exception handling across diverse persistence tools: Spring's generic DataAccessException will be thrown by JDBC-based DAOs as well as Hibernate-based DAOs or any others. Even with Hibernate3's unchecked exceptions, DAO callers should not be tied to HibernateException (when handling specific exceptions); else they would have to be adapted when your DAO implementation changes (e.g. to JDBC).
    There are even negative effects like the one you've indicated, that Spring falling behind a major release of the APIs it wraps.

    Actually, Spring does not really wrap APIs like Hibernate's, at least not in the traditional sense. Spring's Hibernate support mainly manages Hibernate Sessions for you and provides generic transactions that Hibernate access can seamlessly participate in. In terms of actual data access operations, native Hibernate operations are offered, not some higher-level abstraction.

    There are various ways to code actual Hibernate access within Spring's Hibernate support: use HibernateTemplate's convenience operations (mirroring the operations of a Hibernate Session), implement a HibernateCallback (exposing a native Hibernate Session to perform your calls on), or code classic Hibernate access (only fetching your Session reference from Spring's SessionFactoryUtils.getSession).

    So in general, if a new version of Hibernate provides new operations that are not offered on Spring's HibernateTemplate, simply use a HibernateCallback and invoke any desired native Hibernate Session functionality. You will still benefit from Spring's resource management, of course, properly participating in any kind of transaction.

    Hibernate3 is a special case, unfortunately: Hibernate's API has changed in a non-backwards-compatible fashion, even using a different package name. So we need to provide a separate set of support classes for Hibernate3 (essentially a straightforward port of the current Hibernate 2.1 support), which will be publically available as of Spring 1.2 (with first nightly snapshots in a couple of days, and a 1.2 release candidate by end of March).

    Of course, such major API changes in underlying tools don't happen on a regular basis, so the availability of appropriate support classes in Spring is often a non-issue. For example, JDO 2.0 does not enforce any changes in Spring's JDO support, because the JDO API remains backwards-compatible. The only things we will provide there are new convenience methods enabled by JDO 2.0 API refinements.

    Juergen
  41. Spring and Hibernate3[ Go to top ]

    The Hibernate guys themselves say that you should always execute your data access operations within transactions. Transactions are not some rare requirement; they are a necessity.

    Can you elaborate? Why do data reads need to be in transactions? Just for read consistency?

    So should we forgo declarative transaction management and just start the transaction with a Filter like the OpenSessionInView Filter? Does Spring provide support to decide whether we should commit (if there were any write operations) or rollback (if it was all read-only)?
  42. Spring Templates[ Go to top ]

    We talked about this some in our Spring integration chapter in Hibernate Quickly, but the easy way to introduction Spring into a 2.x Hibernate project is to just use the HibernateTemplate's, if only for simplifying resouce clean up code. It turns something that looks like this

    Listing A - Writing your own resource cleanup and transactions

    Transaction tx = null;
    Session session = null;
    try {
      session = sessionFactory.openSession();
      tx = session.beginTransaction();
      session.save(myDomainObject);
      tx.commit();
    }catch(HibernateException e){
       tx.rollback(); // Yes I know this throws a checked exception.
      throw new RuntimeException(e);
    } finally{
      // Ditto here on the checked exception
      if(session != null){ session.close(); }
      
    }


    Into this...

    Listing B - Using Spring for resource cleanup and transactions

    HibernateTemplate template = new HibernateTemplate(sessionFactory);
    template.save(myDomainObject);


    Now admittly, you could certainly simplify listing A yourself, but why bother?
  43. ^_^[ Go to top ]

    yup it's interesting
  44. hibernate 3 - one other point[ Go to top ]

    the author suggests using hibernate3, but if you are using spring and it's hibernate integration, you cannot do this, since the entire package structure changed. spring 1.2 will support hibernate 3, but i don't know when we'll see spring 1.2

    Right, like I mentioned this is for a large application that's already built on CMP Entity beans. They don't have Spring in there, and I don't think introducing Spring at the same time as Hibernate is going to happen, so this isn't a concern. The lack of Spring support is what's kept me from personally switching to H3 yet, though.
  45. Spring and Hibernate[ Go to top ]

    Spring 1.2 will support Hibernate 3. We already have the code in place. We plan to release 1.2 RC1 next month. We cannot do a production release of the Spring integration until Hibernate 3 is final, but we expect that Spring 1.2 final will be available in a similar timeframe to Hibernate 3 final.
  46. No need for wrappers[ Go to top ]

    Note that Hibernate3 now throws RuntimeExceptions, has its own SQLException wrappers, and integrates directly with JTA (auto-flush and auto-close of Sessions), without the need for any additional wrapping.

    Startup of Hibernate is as always one line of code, either in a JMX service or in a static block in a helper class. Check the first documentation chapter.

    Hibernate3 also has more sensible defaults in many cases, e.g. for the fetching strategies or detection of transient instances.

    So, after talking and listening to hundreds of developers in trainings, conferences, forums, etc, we hope that Hibernate3 is the easiest to use Hibernate version so far. It definitely is a good sign if you can remove (boring) parts of the documentation :)
  47. Spring and Hibernate[ Go to top ]

    Is the code already in spring CVS tree somewhere?
  48. Spring and Hibernate[ Go to top ]

    Spring's Hibernate integration has been officially supported and released since Spring 1.0. You'll want to download the latest Spring release from http://www.springframework.org.
  49. Oops![ Go to top ]

    I believe you meant Hibernate 3 support. :-)
  50. segment isolation[ Go to top ]

    I think until hibernate fully supports stored procedures (read somewhere that hibernate 3 has some support built in, but does not support stored procs that return values), a significant segment of the market will be isolated from it....
  51. segment isolation[ Go to top ]

    a significant segment ?

    I have heard many people bring this issue up - yet I have encountered very few examples of where it is actually necessary - or workable.

    Why do you want this?

    -Nick
  52. segment isolation[ Go to top ]

    a significant segment ?I have heard many people bring this issue up - yet I have encountered very few examples of where it is actually necessary - or workable.Why do you want this?-Nick
    I really like Hibernate, but I partly agree. In SQL (Oracle at least), you can have such a stored proc that calculates a value and returns it. Then you can use that stored proc in the select clause of your sql statements (we're using this in a few places in our code to have the DB build a few complex values on the fly). It is already possible to do this with Hibernate as you can direcly use any SQL statement in your Hibernate code (session.connection().prepareStatement()). But a way to call these stored proc from HQL would be nice to have.
  53. segment isolation[ Go to top ]

    I think until hibernate fully supports stored procedures (read somewhere that hibernate 3 has some support built in, but does not support stored procs that return values), a significant segment of the market will be isolated from it....
    It must be possible to use it with named entities in SQL query. One of ways to use procedure is to call it in inline view
    " SELECT proc.* FROM ( myProcedure(?) ) AS proc "
  54. Hibernate Performance Tips[ Go to top ]

    The roadmap says that there will be a release in q1 '05, how close are the hibernate team to an RC or even a 3.0 release?
  55. My personal performance tip for Hibernate would be to try IBATIS once instead. And then compare.

    Wolfgang Gehner
    www.infonoia.com

    (sample Struts 1.3 project in Infonoia Community uses IBATIS)
  56. My personal performance tip for Hibernate would be to try IBATIS once instead. And then compare. Wolfgang Gehnerwww.infonoia.com(sample Struts 1.3 project in Infonoia Community uses IBATIS)
    For obvious reasons, I would have to recommend using O/R Broker instead, if proper domain object design is of any concern.
  57. My personal performance tip for Hibernate would be to try IBATIS once instead. And then compare.

    Here is a link to get you started, but I hope you try for yourself:

    http://sourceforge.net/forum/message.php?msg_id=2695900

    .V
  58. Hibernate Performance Tips[ Go to top ]

    In my experience, the fastest O/R mapping code is a hand written semi-generic O/R mapping layer/framework.

    Yes, it takes some time in the start to develop it, but not too much as layer should be semi-generic with a lot of reusable code, but not a full blown O/R mapping solution.
    Layer is ususaly divided between mappers (which do caching, concurrency control, optimistic concurrency control, transactions) and gateways (which perform raw JDBC data acceess).
    You start with the specific code and as the project goes on and the variety of entities are increasing, you extrect common code to generic classes.

    After that, adding new entities to the mapping is not more time consuming then in full-blown generic O/R mappers. And you have all the power and control you need to tweek the DB access code (and this is always needed).
    Of course, this is not for novices in the O/R mapping arena.
  59. the real catch[ Go to top ]

    In my experience, the fastest O/R mapping code is a hand written semi-generic O/R mapping layer/framework.Yes, it takes some time in the start to develop it, but not too much as layer should be semi-generic with a lot of reusable code, but not a full blown O/R mapping solution.Layer is ususaly divided between mappers (which do caching, concurrency control, optimistic concurrency control, transactions) and gateways (which perform raw JDBC data acceess).You start with the specific code and as the project goes on and the variety of entities are increasing, you extrect common code to generic classes.After that, adding new entities to the mapping is not more time consuming then in full-blown generic O/R mappers. And you have all the power and control you need to tweek the DB access code (and this is always needed).Of course, this is not for novices in the O/R mapping arena.

    the real catch is the person writing the mapping code by hand. If it's someone who is highly skilled with lots of experience, than I would say it's about the same. If it's an average developer, who doesn't know much, often it ends up being a mess. This is from first hand experience. I hand written mapping can easily degenerate to unmaintainable code very rapidly. Especially if the specifications change rapidly and the group is "large". large depends on the case obviously :)

    peter
  60. ooops typo[ Go to top ]

    I meant "A hand written mapping can easily degenerate..."
  61. In my experience, the fastest O/R mapping code is a hand written semi-generic O/R mapping layer/framework

    Specialized code will always be faster, the trouble is it requires quite a bit of programming. Would it not be nice if a framework generated bytecode at runtime to map a specified bean to a specified table using just the method calls. e.g.
        bean.setFirstName(rsSelect.getString(1));
        and
        ifs1 = bean.getFirstName( != null)
             psInsert.setString(2, s1);
        else
             psInsert.setNull(2, 12);

    This is exactly what http://jdbcpersistence.dev.java.net/ does for you. In addition, it allows you to map just the interface or an abstractclass. The framework will generate the implementation in bytecode at runtime.
    Fully decompiled code for typical user bean would look like this after decompilation:
    http://www.codegeneration.net/articles/rojkov/ExampleUserBeanJDBCPersistor.jad

    I used to use Hibernate until I got annoyed by it taking up 10+ sec or more every time you startup your application.

    http://jdbcpersistence.dev.java.net/
    http://www.codegeneration.net/tiki-read_article.php?articleId=%2067

    Alex
  62. Specialized code will always be faster

    That makes a big assumption on the quality of the developer writing the specialised code.

    My observations suggest otherwise.

    And evern if they could, you want developers that good writing code that actually makes you money, rather than generic persistance code...

    -Nick
  63. More logging[ Go to top ]

    I just started to use hibernate (2.1.8) and it works fine. I was wondering if there is any way to set up the logging so that actual parameters used by the query are also logged.
    E.g:
    Hibernate logs the sql as

    insert into abd values (?, ?, ?)
    select a, b, c from abc where a=?

    I would like to have

    insert into abd values (?, ?, ?) [1, 5, 'abcdef']
    select a, b, c from abc where a=? [1]


    Is there any way to get the actual values used by the sql as some times same query runs slow and It could be because of the values being used. Any way it is big help for debugging.
  64. More logging[ Go to top ]

    This is not an O/R mapper concern IMHO but has rather to do with the JDBC driver itself.

    I have developped a wrapper JDBC Driver (I mean a Driver over a Driver) that, among many other things (like support for positional parameters and adaptative behavior) , can not only log you the SQL statement but also the bind parameters as they are set. We found this very usefull in the three projects that were built on top of this driver (not an open source one though, I'm trying hard to make it open source).
  65. More logging[ Go to top ]

    This is not an O/R mapper concern IMHO but has rather to do with the JDBC driver itself.I have developped a wrapper JDBC Driver (I mean a Driver over a Driver) that, among many other things (like support for positional parameters and adaptative behavior) , can not only log you the SQL statement but also the bind parameters as they are set. We found this very usefull in the three projects that were built on top of this driver (not an open source one though, I'm trying hard to make it open source).

    How about a custom implementation of the PreparedStatement that wraps the standard and provides a toString() that outputs the statement. I found some come some years ago that on the javaworld website that does just that. You'd do something like
     
        String queryStr = "select * from table where col = ?";
        PreparedStatement stmt = StatementFactory.getStatement(connection,queryStr,DebugLevel.On);
        stmt.setInt(1,value);

        log.debug(stmt);

    I've always thought that with some modifications for other DBs(currently supports on Oracle because of data formatting), that it could be folded into Hibernate.
        stmt
  66. More logging[ Go to top ]

    I just started to use hibernate (2.1.8) and it works fine. I was wondering if there is any way to set up the logging so that actual parameters used by the query are also logged. E.g: Hibernate logs the sql asinsert into abd values (?, ?, ?)select a, b, c from abc where a=?I would like to haveinsert into abd values (?, ?, ?) [1, 5, 'abcdef']select a, b, c from abc where a=? [1]Is there any way to get the actual values used by the sql as some times same query runs slow and It could be because of the values being used. Any way it is big help for debugging.
    in your log4j.properties:
    log4j.logger.net.sf.hibernate.type=debug (or whatever level you want)

    I've seen a lot of "in-house" ORM mappers. and i am happy i can use Hibernate now.

    pascal
  67. Hi Pascal,

    JXInsight (JDBInsight) provides a comprehensive performance management and distributed tracing solution with special callstack classifications (Hibernate, JDO, EJB, JTS, Servlets) and UI visualizations for Hibernate.

    JDBInsight (a subset of JXInsight) provides system properties for configuring whether parameters are binded and recorded in the SQL statistics in the profile and timeline snapshot modes.

    jdbinsight.server.jdbc.preparedstatement.intercept=true
    jdbinsight.server.jdbc.preparedstatement.bindvalues=true
    jdbinsight.server.jdbc.preparedstatement.set.intercept=true
    jdbinsight.server.jdbc.preparedstatement.unbindvalues=false
    jdbinsight.server.jdbc.callablestatement.intercept=true
    jdbinsight.server.jdbc.callablestatement.unbindvalues=false
    jdbinsight.server.jdbc.statement.intercept=true
    jdbinsight.server.jdbc.statement.unbindvalues=false

    An unique feature of our tool is that we are able to correlate memory allocations, thread events, cpu, clock, and gc statistics at the resource transaction level while providing a transaction analysis of the Hibernate or JTS transaction execution patterns.

    We currently provide the following distributed trace integrations:

    Servlets/JSP
    JNDI
    CORBA PortableInterceptors
    EJB Home and Remotes
    Logging and Log4j
    JDBC
    HP OpenView SD 4.5

    with other trace integrations planned in the coming weeks including:

    Hibernate (Session)
    JDO
    JAX-RPC
    JMS

    Please read the following links for additional information:

    http://www.jinspired.com/products/jdbinsight/downloads/new-in-3.1.html
    http://www.jinspired.com/products/jdbinsight/downloads/new-in-3.0.html
    http://www.jinspired.com/products/jdbinsight/downloads/index.html


    Regards,

    William Louth
    CTO, JInspired

    "J2EE tuning, testing and tracing with JXInsight"
    http://www.jinspired.com
  68. More logging[ Go to top ]

    Check out http://www.p6spy.com
    Regards
    Howard
  69. Transactional 2nd Level Cache[ Go to top ]

    Anyone knows why he goes for Coherence for a transactional 2nd level cache and does not even mention JBossCache (http://docs.jboss.org/jbcache/TreeCache.html) which should do the trick as well?
  70. Transactional 2nd Level Cache[ Go to top ]

    Anyone knows why he goes for Coherence for a transactional 2nd level cache and does not even mention JBossCache (http://docs.jboss.org/jbcache/TreeCache.html) which should do the trick as well?

    Because

    1. I haven't heard anything good about the JbossCache implementations performance

    2. It's pretty new, and, like a database, you don't want to be the one finding pesky bugs in a transactional cache

    3. Coherence does cool things like let you cache outside of the JVM heap so you don't incur the garbage collection hit

    4. Cameron gave me a nifty shirt once (hint hint Cameron)
  71. Transactional 2nd Level Cache[ Go to top ]

    2. It's pretty new, and, like a database, you don't want to be the one finding pesky bugs in a transactional cache

    Yep, we're using JBossCache with Hibernate and Spring in a medium sized application, and have had locking issues which we've had to fix ourselves, as well as some difficulties with starting a discussion about getting these fixes included in upstream.

    If only Coherence had cheap academic licenses...
  72. Transactional 2nd Level Cache[ Go to top ]

    Hi Mikael,
    If only Coherence had cheap academic licenses...

    As my dad always says, "If you don't ask, the answer is always no" ;-). Drop me a line at rmisek at tangosol dot com.

    Later,
    Rob Misek
    Tangosol, Inc.
    Coherence: It just works.
  73. Issues using Hibernate with the web layer[ Go to top ]

    One of the problems when using ORM like hibernate is the detached object. Rarely, does the domain object map one to one from the UI layer to the database (or domain object). It seems VERY dangerous to call the saveOrUpdate routine in hibernate because it is expecting a complete DTO object (the whole object graph) to be reconstructured from the UI. I'm wondering on how other people are developing web applications using hibernate deal with this issue. It is a source of confusion and frustration for the developers in my group on how to deal with this problem.

    The Hibernate in Action book does not give enough practical examples on how to deal with this issue.

    The other problem with the web layer are the lazily defined relationships. Developer run into the constant problem of the initialization failure because they "forgot" to initialize the relationship for a specifc view. It seems to me that having a complex object does not blend well into a web layer architecture because in the end you are writing perverse code to deal with this problem (like to doing dummy calls to the lazy relationship to instantiate it).


    Comments?

    Dino
  74. I can recommend reading chapter 8 again, these questions are discussed for about 40 pages.

    Some readers say we didn't give a yes/no answer what to use (DTOs, Detached Objects, Long Session, etc.) but this is intentional, all are useful in their own way and have a different impact on the fetching strategies you'd apply. This deserves more coverage but the persistence layer needed explanation first :)
  75. Thanks Christian,

    I will re-read that Chapter again. There are places in our code where Hibernate fits beautifully, but other places it is somewhat more difficult. I'm encouraging my guys to retrieve the domain object from the hibernate session and update the fields "manually". It seems to be the most reliable and less-error prone way to update data. Otherwize, my juniors would wipe out chucks of data because they "forgot" to load the data in the UI and propagate in the MVC action. I would love for you guys to explain in more detail about detached objects especially when objects are complex but the UI is somewhat simple.

    I have this issue as well. I have numerous one-to-many relationships from the parent to different children tables. Do I map all the different one-to-many relationships in the domain object? What are your suggestions?

    Dino
  76. Web-app with hibernate is easy.
    I work with struts, and just "inject" my pojo graph in the jsp a simple servlet filter allows to avoid LazyInitialisationException, just check open session in view pattern.

    You're talking about DTO, i try not to use DTO, DTO are done for ejb1 and 2.
    So i just use a root object as a property of a DynaValidatorForm.
    Then i really like using long session per application transaction pattern, using it, persistence is really transparent, you just have to fix one action as a _global_commit_ action.
    Detached objects are not so evil and you may need them if you need failover (reduce httpSession size).
    Long session per application transaction pattern is great, it is explained in Hibernate in action + caveatemptor show a simple example with HibernateUtils class and HibernateLongFilter class.

    Anthony
  77. Issues using Hibernate with the web layer[ Go to top ]

    One of the problems when using ORM like hibernate is the detached object. Rarely, does the domain object map one to one from the UI layer to the database (or domain object). It seems VERY dangerous to call the saveOrUpdate routine in hibernate because it is expecting a complete DTO object (the whole object graph) to be reconstructured from the UI. I'm wondering on how other people are developing web applications using hibernate deal with this issue.
    One of ways is to use "DTO" without "domain objects". It is not the shame to map "value model" directly (database is the real domain model).
  78. JPA Can be ~15 times faster...[ Go to top ]

    We have released Batoo JPA that is ~15 times faster then Hibernate and implements the JPA Spec %100. The main motivation of the project was all three JPA implementations are simply put slow. Having realized JPA could be much faster, we have developed Batoo JPA. Give it a try http://batoo.jp