Spring, Hibernate and Velocity
Posted by Kelvin on 21 Nov 2004 at 07:30 pm | Tagged as: work, programming
I've been busy getting Spring, Hibernate and Velocity working, so some rants about it..
When I started using Torque as an OR tool, I really liked the its query-by-criteria system, but disliked the fact that code generation had to be done, and that every domain object effectively became five objects (Person, PersonPeer, BasePerson and BasePersonPeer and PersonMap). Also irritating was the compulsory inheritance from a persistence-based superclass, which seemed to be an abuse of inheritance, and takes away your only chance of inheritance in Java. I also didn't like the fact that all domain objects were placed into an om
package. After a while, it just gets really unmanageable.
So, I was really thrilled when I discovered Hibernate. No more code generation, no more persistence-class inheritance and my objects could live anywhere they wanted.
Spring recommends a differentiation between POJOs, DAO classes (like Torque Peers), service objects (where business logic and transactions resides) and the web layer. As you'll see from the jPetstore demo, the objects are also placed into these packages accordingly.
One huge difficulty I ran with Spring and Hibernate was lazy instantiation of collections. Hibernate's sessionfactory is managed by Spring, so unless an object is created by Spring, there's no easy way of getting hold of a Hibernate session. Technically, POJOs aren't supposed to even know about sessions. HOWEVER, with a lazily instantiated collection, the same session that opened the proxy must be still open when getCollection()
is called on the collection, and that's a big problem. when the poor POJO has no reference or knowledge about the session.
This is well documented at these links, with some workarounds suggested
http://thread.gmane.org/gmane.comp.java.springframework.user/3513
http://thread.gmane.org/gmane.comp.java.springframework.user/3402
http://forum.springframework.org/viewtopic.php?t=1640&highlight=hibernate+dao&sid=828d4100ba2f6f8dffc7f06bc7054857
http://forum.springframework.org/viewtopic.php?t=1805&highlight=hibernate+dao&sid=828d4100ba2f6f8dffc7f06bc7054857
http://forum.springframework.org/viewtopic.php?t=301&postdays=0&postorder=asc&highlight=hibernate+dao&start=0
So, I've had to compromise and remove the lazy instantiation and perform it via the DAO instead. Yucky, but lazy instantiation's really important for that object, and I really like Spring's wrapper around Hibernate.
Something else I worked on was porting Velocity Tool's VelocityLayoutServlet to Spring, so template layouts are possible once again, plus use of tools in templates.
Comments Off on Spring, Hibernate and Velocity