Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple Hibernate List Example  RSS feed

Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm posting this example because I encountered a very subtle problem when I tried to implement a list in Hibernate.

In my day job, I spent several days tracking down a very bizarre bug. When I would do something in one class, I would get errors in a completely different, and completely uncoupled, class. There were no error messages; I just couldn't get the persistence to work properly.

I had two completely unrelated classes. Call them "ClassA" and "ClassB". I also had a third POJO class "ClassC" that was contained by ClassB (and is completely unrelated to ClassA) in a java.util.List. This is what I was encountering most of the time: If I had just one instance of ClassA in persistence (or if I commented ClassA out completely), Class B was fine. If I had two or more instances of Class A in persistence, Hibernate would create create an instance of ClassC, and place it multiple times in my java.util.List! I spent several days tracking this down, and finally figured it out: I needed to add a @OrderColumn annotation to the list.

The lesson I learned the hard way is: If you have a java.util.List set, be sure to include a @OrderColumn annotation on it. If you don't, you won't get any error messages, but you will get very strange behavior.

This is the container class. The interesting bit is line 9. Also, lines 30-35 ensure the sequence is correct.

This is the contained class:

This is an example of how to use the classes:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!