Wednesday, October 05, 2005

EJB3: @OneToMany and @OrderBy - Set versus List

I noticed that my (Hibernate) EJB3 entity with a @OneToMany collection did not sort correctly even though I had an @OrderBy("sortcolumn") specified on it. Every time I fetched the entity from database, the collection order was randomly different. The reason was that the collection was declared as java.util.Set, and a Set does not guarantee that the order will remain constant over time. The database performed the order by statement, but the Set did not return elements in the same order from time to time. Changing the collection type to java.util.List solved the problem, the sort order remained constant.

Introduction

My name is Göran Ehrsson. I live in Sweden, Scandinavia and was born in the mid 60's. I'm an enterprise systems architect and have been developing enterprise systems since 1988. In the beginning it was C++, but in late 90's focus shifted to Java and J2EE. I started this blog to share knowledge and experience in software development using Java technology. My success in software development are very depending on articles found on Internet. I own a lot of Java books, but for fast answers, the Internet is outstanding. I would never been where I am today without Internet and search engines. Although my professional job as senior (CRM) systems architect is interesting and gives great real world experience, it has not satisfied my personal need for cutting edge research and development. Therefore most of my knowledge has been gathered at home, at night, when the rest of the family are sleeping... This blog is my way of giving back to the development community what I have learned during 20+ years of software development. It will hopefully include articles about J2EE, EJB3, JBoss, Hibernate, Spring, J2ME and Jini.