tags:

views:

32

answers:

2

Hi all,

My google-fu is failing me in this. I'm doing a small database app which reads some data from a file along with some meta data that I currently store in a Map in my entity. I'm getting fed up with it always being displayed in a random order.

So can I use a LinkedHashMap or @OrderColumn with Maps somehow to preserve insertion order?

@Entity
public class MooData
{
    @OrderColumn
    @ElementCollection
    private List<BigDecimal> data;

    @ElementCollection
    private Map<String, String> properties;
}

:)

A: 

My google-fu pointed me to some pages, where they say that @OrderColumn can be used for all collections - so it sounds like it's not restricted to lists or sets. Although all of the pages I found so far have examples with List fields.

The eclipse WIKI has a nice article on the @OrderColumn annotation.


Edit

What about a workaround - you could add a method to your bean to get the maps entry set:

public Set<Map.Entry<?,?>> getPropertiesEntries() {
   Set<Map.Entry<?,?>> result = new TreeSet(myComparator);
   result.addAll(map.entrySet());
   return result;
}

and use this entrySet whenever you loop through the map.

Andreas_D
Maps dont inherit the Collection interface which is is what I think a requirement for the @OrderColumn
willcodejavaforfood
Ahh, yes, you're right...
Andreas_D
+2  A: 

I can't find any evidence in the JPA 2.0 spec that the @OrderColumn annotation is supposed to work for Map. Quoting the spec:

11.1.39 OrderColumn Annotation

The OrderColumn annotation specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list. The OrderColumn annotation may be specified on a one-to-many or many-to-many relationship or on an element collection. The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered. The order column is not visible as part of the state of the entity or embeddable class.

If you want to preserve order, use a List (of Embeddable in your case). With a Map, access to values by keys.

Pascal Thivent
Kind of suspected that. I'll rewrite it as a List then :) Cheers Pascal
willcodejavaforfood