Hibernate collection types and Seam

By default Seam maps all of your Hibernate collections as Sets. This is also the most common Hibernate collection type. Keep in mind though that this may not always be the collection type you need.

The other day I was working on a project and I was adding objects to my collection and displaying them in the view. I noticed however in the view that they weren’t displaying in the order that they were added. After scratching my head for a while I finally realized that it was because they were being added to a Set which doesn’t preserve the order of the elements. To resolve the problem I simply changed my collection type from Set and List in my Entity class.

Here is a quick rundown of the collection types supported by Hibernate. For more detailed information check the Hibernate documentation.

  • A java.util.Set is mapped with a <set> element. Initialize the collection with a java.util.HashSet.
    • The order of its elements aren’t preserved.
    • Duplicate elements aren’t allowed.
    • This is the most common persistent collection and the default collection type for Seam.

  • A java.util.SortedSet is mapped with a <set> element. Initialize the collection with a java.util.TreeSet.
    • The sort attribute can be set to either a comparator or natural ordering for in-memory sort.

  • A java.util.List is mapped with a <list> element. Initialize the collection with a java.util.ArrayList.
    • The position of each element is preserved with an additional index column in the collection table.

  • A java.util.Collection is mapped with a <bag> or <idbag> element. Initialize the collection with a java.util.ArrayList.
    • Allows possible duplicates.
    • The order of the elements aren’t preserved.
    • Uses a list internally but ignores the index of the elements.

  • A java.util.Map is mapped with a <map> element. Initialize the collection with a java.util.HashMap.
    • Preserves key and value pairs.

  • A java.util.SortedMap is mapped with a <map> element. Initialize the collection with a java.util.TreeMap.
    • The sort attribute can be set to either a comparator or natural ordering for in-memory sort.

  • Arrays are supported as well by Hibernate however they are rarely used and aren’t supported by the JPA standard.


Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Brian

Brian Abston is a Java Developer in Oklahoma who also loves technology.