Hibernate Gotchas to Watch out

I’ve been using Hibernate for some time now and when I don’t work on a hibernate project for a while I find myself doing the same mistakes I did the previous times.

So here is a sort of watch list for my self hopefully will be useful to someone else as well.

Implement hashCode and equals

You should always implement these methods in general but for your entities you should pay a bit more attention.The first thing you think when I say equals is probably to use the Id to distinguish between instance. Well, that’s gonna cause you a lot of troubles.
You need to keep in mind that you are working with db entities and not normal POJOs.

When Hibernate is fetching objects is your using collections and hence equals and hashCode to know if an object you are looking for is in the session. For new objects id will be null or 0.
That means when trying to save two objects of the same class the second is going to overwrite the first one.
Also when hibernate saves a new instance it will set the id, thus making it a different object while it is exactly the same.
You need to use some business keys. Unique codes are great but if you can’t think of anything just use a meaningful field and some timestamp (like creation date) to make it unique.

This is a good reference if you want to understand a bit further what’s happening.

Careful with One-to-One and Many-to-One relations

 

This is something you really need to know.
When mapping a relation as One-to-One or Many-to-One on the “One” side of the relation you can’t have lazy loading unless you specify the field as not nullable.

Why is that?

Essentially on the many side of the relation hibernate can use collection proxies and lazily load instances when required. On the “One” side there is no collection interface but instead a reference to one of your model classes.

Hibernate can proxy that one as well but only if it is sure the reference will never be null!
So remember if you want to have lazy loading use the not null on the one side together with the lazy annotation (or xml equivalent).
If your relation can be null but you still really want to make it lazy then you have some options:

  • Create a value to represent that. For example if you have a relation like Person ->Partner  just use a specific instance of Partner that means “no partner”.
  • Use build time instrumentation. Check this
  • Fake the one side using a List and getting the field with get(0)

Read more on the hibernate documentation.

Enable the statement logging

This is the only way to verify Hibernate is really doing what you expect him to do. Luckily enough there are different logging parameters that you can use to find out what is happening both at the HQL or if you want at the SQL level. You’ll be surprised how many times hibernate is running queries and you did not except it. Try to this from the very beginning and help the team understand the importance of having the best and least possible queries or you’ll surely have performance issue when running the application on some real data. To enable logging just set this property in the session configuration file

hibernate.show_sql=true

If you want to see it nicely formatted add

hibernate.format_sql=true

Watch what goes in the toString method.

 

This one is again related to what Hibernate fetches for you without you really being aware. Lots of times when you see queries but can’t figure out why some lazy list is being loaded then check the toString method.
It might be the culprit!

What are your hibernate gotchas?

Reference: Hibernate Gotchas! from our JCG partner at the Development in progress blog.

Related Articles :
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


2 + five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books