开发者

Sorted map of Java primitives using JPA2 and Hibernate?

开发者 https://www.devze.com 2023-03-23 17:39 出处:网络
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:

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!


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

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

per the annotations reference.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号