代码之家  ›  专栏  ›  技术社区  ›  mancioshell

[GAE-Objectify]:LinkedHashMap不尊重键的顺序

  •  0
  • mancioshell  · 技术社区  · 10 年前

    我正在使用Objectify访问Google App Engine应用程序中的DataStore。

    我有两个实体:

    @Entity
    public class Client {
        @Id String id;
    }
    
    @Entity
    public class Queue {
        @Index @Id String name;     
        @Load LinkedHashMap<String,Ref<Client>> clientsInQueue;
    }
    

    在事务中,我执行如下操作:

    Client newClient = new Client(...);
    ofy().save().entity(newClient);
    
    Queue selectedQueue = ofy().load().type(Queue.class).id(queueName).now();
    selectedQueue.getClientsInQueue().put(newClient.getId(), Ref.create(newClient));
    

    但是当我试图打印LinkedHashMap中的所有元素时,我注意到这些元素正好位于 颠倒 顺序

    例如,如果我在LinkedHashMap中添加2个客户端并保存它,如下所示:

    Queue selectedQueue = new LinkedHashMap<String,Ref<Client>>();
    String id1 = "id1";
    Client c1 = new Client(id1);
    ofy().save().entity(c1);    
    String id2 = "id2"
    Client c2 = new Client(id2);
    ofy().save().entity(c2);    
    
    selectedQueue.getClientsInQueue().put(c1.getId(), Ref.create(c1)); 
    selectedQueue.getClientsInQueue().put(c2.getId(), Ref.create(c2));
    ofy().save().entity(selectedQueue); 
    
    Set<String> keys = selectedQueue.getClientsInQueue().keySet();
    
    for(String key : keys){
        Client c= selectedQueue.getClientsInQueue().get(key).get();
        log.info("id: "+c.getId());
    }
    

    结果是:

    编号:id2

    编号:id1

    为什么我会获得这种行为?我知道LinkedHashMap必须维护密钥的顺序!在GAE数据存储中使用LinkedHashMap有问题吗?

    提前感谢。 干杯 亚历山德罗。

    1 回复  |  直到 10 年前
        1
  •  2
  •   stickfigure    10 年前

    类型的字段 Map<String, ?> 作为类型存储在低级api中 EmbeddedEntity ,是唯一可用作属性的类似地图的结构。这 嵌入的实体 实现为非链接 HashMap 因此,客观化无法维持秩序。

    我将在Objectify的文档中记录这一点。如果您希望更改此行为,请在GAE的问题跟踪器中打开一个问题,请求“实体和嵌入实体应使用LinkedHashMap来保持顺序”。