Skip to content


12 things I bet you didn’t know about Hibernate

I’ve been working with Hibernate for the past 2 years, doing multiple projects with the framework. With this experience, I thought I pretty much had Hibernate figured out and knew what was possible and what wasn’t. Now this month, I have been prepping for a course I’ll give about the framework and to my great surprise I actually learned a lot! I’m more then happy to share some of this new cool stuff I’ve found out!

noop field type

noop field’s are columns that exist in the database, but not in your class. Sometimes handy for calculated values are connecting to legacy databases. We actually encountered such a use case, where the data conversion from an old application gave some data which we didn’t want to see or alter in the new application. But as a reporting query, we did want to show which data was old. We actually didn’t use the noop (didn’t knew about it), but it would have made a great use case.

NamingStrategy

In my first project, we declared naming standards for tables and column. Although we abide them, we did it manually. The NamingStrategy would let us declare those standards automatically. In our use case, we suffixed Boolean columns with _B, and enum states with _S , etc… . A good NamingStrategy would have done this automatically.

Bags don’t need to be loaded when inserts happen

Since no filtering or ordering is required, one can insert data into a Bag, without triggering the lazy loading of the entire bag. This is, in a lot of use cases, a great performance gain. In our teams, we do batch processing regularly where we insert a lot of data. This would have been faster if we used the Bag interface (instead of the more common Set).

Replicating

You can compare it with merging, but only you are not reattaching a detached object, you are attaching an object with a different database. Never ever had to use this, but it was still a gem I didn’t know about.

Persist() vs save()  (persist does not cascade)

I just didn’t know this. What would be a good use case for this?

.addEntity

session.createSQLQuery(
“select {c.*} from CATEGORY {c} where NAME like ‘Laptop%’”
).addEntity(“c”, Category.class);

HQL new keyword

I’m absolutely crazy about this one. Following is a standard idiom in the projects I’ve worked in: we do some search query with HQL and we map, by hand, the result into our own custom created result object. All the mapping, type conversion etc we do is just a waste of time! Don’t know what I’m talking about? Here is an example:

select new UserSearchResult(u.id, u.name, u.birthDate) from User u where …

The UserSearchResult is a plain POJO (with either needs to be declared or fully qualified). The solution is simple and clean. Absolutely love it!

Query.setProperties()

This one is also a type-safer (as in life-saver). Fill in the entire object and let HQL get the values by reflection. Beats the hell out of determining setString or setDouble etc.

Item item = new Item();
item.setSeller(seller);
item.setDescription(description);
String queryString = “from Item item”
+ ” where item.seller = :seller and item.description like :description”;
session.createQuery(queryString).setProperties(item);

It again safes you some typing.

Query hints

FlushMode: very good for search results and batch jobs (will not trigger a flush before the query)

setReadonly: very good for search results (disabled dirty checking)

setTimeout: a default should be set for every query.
Actually this is very important. We have had applications which, due to bug or db crash, kept a lock for hours. No (normal) query should take more then, oh lets say, 60sec. Setting the timeout on all query to this is a safe precaution.

Using named queries

Using named queries abstracts the query definition from your DAO layer. I believe this to be a nice addition, something that could be done after the implementation. You can define the query on class level (in the class.hbm.xml) or on an application wide scope, so you can reuse them across multiple DAO’s. Never actually came across a query I’d reuse across multiple dao’s though…

MatchMode.START

On most of my projects we write a DaoUtil that would prefix/suffix the search input, with the right wild card. Now it seems Hibernate provided a shortcut to this (all along).
e.g. Restrictions.like(“streetname”, “G”, MatchMode.START)

Projections.projectionList

This let’s you search on some fields, instead of complete objects using Criteria. I’ve always found it strange that Criteria queries only returned complete objects. Seems that my ignorance was to blame :)

session.createCriteria(User.class)
.setProjection( Projections.projectionList()
.add( Property.forName(“id”) )
.add( Property.forName(“username”) )
.add( Property.forName(“birthDate”) )
);

Conclusion

Never too old to learn? :)

You can’t learn everything the first time round. It’s only after larger experience you truly start to see all the finesse of a framework. I truly believe in studying everything twice. With Spring, I had the same insight after going back 2 basic on it after doing a complete project with it. Now with Hibernate, I see the same enlightement for me.

Posted in jboss.


14 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Joram Barrez says

    I had a few “oooh nice” moments when reading this post … indeed, never too old to learn.

    I really like this projectionList … could’ve used it like a millions times in the past.

  2. Luke says

    Hi, nice post, and if it’s up to the Named Queries, I believe they do have another nice feature, which is the fact they are validated during the aplication startup (so you won’t end up with queries that refer properties that are not available or so).

    Cheers,
    Luke

  3. Andries Inzé says

    That’s indeed a bonus.

    The downside however is that you can’t change them at runtime while developing.

  4. Moiz Kapasi says

    Awesome list. Many of them were eye openers. I agree with you that the best way to learn something is to relearn it :)

  5. Emmanuel Bernard says

    Persist() vs save() (persist does not cascade)

    This is not true, persist does cascade, it cascades the “persist” operation, not the save one :)

  6. Dan says

    Great tips! One question, will the results of a query using the ‘new’ keyword to return pojos be cached in the hibernate session and re-used by subsequent calls of the same query?

  7. Andries Inzé says

    I have no idea.
    I doubt it however, since the hibernate session is only for attached objects and these aren’t attached.

  8. Bill Gates says

    Thanks for the data!

  9. Jigar Mehta says

    These are really greta techniques that i was unaware of, thanks for bringing them to light.

    I tried using HQL new keyword, i wanted just an id and name form one of my objects. But hibernate asked for a valid constructor when i ran a query like one displayed above. It means it requires a constructor which would take such arguments. It did work after overloading my original constructor.

    But is’nt there a way without creating this constructor, else we would kep creating such constructor as per number and kind of arguments… I hope my concern is conveyed properly.

    Thanks!
    Jigar

  10. Andries Inzé says

    As far as I know, the constructor with the right amount of parameters needs to be provided. It would indeed be a nice feature if it would use the getters/setters.

    Regards

  11. Pramatr says

    This post was worth it even if you only read “Bags don’t need to be loaded when inserts happen”. We had so many problems with performance that were solved when I figured this one out. It was one of those, if I only I’d know this before moments.

Continuing the Discussion

  1. Blog bookmarks 08/27/2008 « My Diigo bookmarks linked to this post on August 27, 2008

    [...] 12 things I bet you didn’t know about Hibernate | Learning by Experience [...]

  2. Блог Зеника » Blog Archive » 12 things I bet you didn’t know about Hibernate linked to this post on August 28, 2008

    [...] витворяємо з Hibernate всякі убер штучки, мені в руки попав лінк на дійсно цікавий список речей які є в Hibernate але ми про [...]

  3. Revue de presse ! - Blog de ZedroS - Club d'entraide des développeurs francophones linked to this post on December 25, 2008

    [...] toujours toute la richesse de Java . – présentation de Scala par Lex Spoon. Eclairant ! – 12 choses surprenantes sur Hibernate – enfin, une présentation de Fan, une sorte de langage Java 2.0, vraiment intéressant. A [...]



Some HTML is OK

or, reply to this post via trackback.