0

I'm using Hibernate 3.6 and JPA2 as part of the Play Framework 1.2. I have an entity class that needs a Double-to-Double map, sorted on the keys. Here's what I've got so far:

@Entity
public class MyEntity extends Model
{
    @ElementCollection
    @MapKeyColumn(name="keycolumn")
    @OrderBy("keycolumn")
    public Map<Double, Double> myMap;   
}

I've got a test set of data being loaded into my DB using YAML, deliberately not in order so that I can verify the sorting is working:

myMap: {100.0: -10.0, 200.0: -5.0, 125.0: -8.0, 300.0: -2.0, 50.0: -12.0}

And unfortunately, so far it's not:

Key: 100.000000, value: -10.000000
Key: 200.000000, value: -5.000000
Key: 125.000000, value: -8.000000
Key: 300.000000, value: -2.000000
Key: 50.000000, value: -12.000000

If the sorting was working, I would expect to see:

Key: 50.000000, value: -12.000000
Key: 100.000000, value: -10.000000
Key: 125.000000, value: -8.000000
Key: 200.000000, value: -5.000000    
Key: 300.000000, value: -2.000000

Databases are not my strong suit, and I'm also fairly new to JPA. Been digging through the Hibernate docs and various forums, with no real luck. Any assistance is greatly appreciated. Thanks!

markerikson
  • 63,178
  • 10
  • 141
  • 157

2 Answers2

0

The quickest way is to make it a SortedMap and use @Sort:

@Sort(type = SortType.COMPARATOR, comparator = WhateverComparator.class)

per the annotations reference.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • Tried creating a DoubleComparator class that implements compareTo() using Double.compare(), but it didn't work. Eventually decided to just take the map that Hibernate gives me, and shove all the values into a TreeMap to give me a sorted map. Thanks, though. – markerikson Aug 01 '11 at 15:43
  • Oh, my bad. For doubles, you could just use SortType.NATURAL. No need to write a comparator. Then Hibernate will essentially do what you're doing manually. – Ryan Stewart Aug 01 '11 at 18:21
  • Having trouble getting that to work in my case. I'm using Hibernate as part of the Play Framework, and loading sample data from a YML file. Play's YML loading code seems to want to load my data as a LinkedHashMap, which results in a ClassCastException when Hibernate tries to treat it as a SortedMap. Oh, well - just being able to sort it at runtime will suffice for now. Thanks anyway. – markerikson Aug 02 '11 at 15:55
0

Following will work in either case where key is primitive wrappers or your custom object implementing comparable. i would avoid comparator and have Object implement Comparable, so that i can simply use

@Sort(type = SortType.NATURAL)

Anil G
  • 1