Hi folks, just picked up the reference doc. from hibernate's homepage. Having gone through few pages and I have two questions wish someone out there could clarify for me.
1. Below are code segment from a utility class for opening and closing session.
My question is why bother with the 'ThreadLocal' technic. I cant see the intention of why coding it in this way. Is there anything wrong with using and straightway?
2. The doc. mentioned that there are tools provided to automate the OR mapping process. I wonder do those tools can actually handle every case perfectly? As a beginner, I know it's good to go through everything by hand. But I wonder how other people really do with it in the commercial development environment. Any inputs are deeply appreciated.
The reverse-engineering tools can be handy if you've got a large established schema that you won't be changing. I've only generated mappings from one schema, and in fact another developer did it and gave me the files. The first thing I did was replace nearly 90% of the mapping, partly so I became comfortable with the mappings, but also because our existing domain objects didn't map exactly to the schema.
It picked up and mapped every relationship. But since I was porting an existing entity bean layer, I had not modeled many of the relationships. Instead. I mapped foreign keys as Integer properties rather than object references. This may be me not fully embracing the Hibernate way, but I'm used to breaking up the model into logic units with relationships only where I want to treat a complete object graph as a unit.
In many cases I want to load an entity without loading all related entities. While I could have used lazy loaded references, it was more that I didn't want the entities to be staticly connected to each other at compile time. Since this is a big app with several other tools working on pieces of it, I didn't want each tool to contain knowledge of the whole model.
The ThreadLocal Session pattern is very handy when you create a DAO layer on top of Hibernate to abstract your domain access layer from the business logic. In this way, you avoid needing to pass a Session to each DAO. Instead, you open and bind a Session to the Thread at the outer edge of your application transactions in your business logic. Now each DAO just uses the Session for that Thread without passing references. This really pays off in spades when using a framework like Spring to manage the entire process (Session and transactions).
While I haven't used it (I use Spring), I believe Hibernate provides a HibernateUtil that does all this work for you. Check out that class and see if that's what it does, as I could easily be mistaken.