简体   繁体   中英

Cast HashMap in LinkedHashMap

I'm getting the results from the database into a List<Map<String, Object>> . The problem the values are not in order, so I thought to cast in a LinkedHashMap, but I get this exception:

 javax.ejb.EJBException: java.lang.ClassCastException: class java.util.HashMap cannot be cast to class java.util.LinkedHashMap (java.util.HashMap and java.util.LinkedHashMap are in module java.base of loader 'bootstrap')

The method is this:

protected EntityManager em;
Query q = em.createNativeQuery("select * from City");
NativeQueryImpl nativeQuery = (NativeQueryImpl) q;
nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<LinkedHashMap<String, Object>> r = (List<LinkedHashMap<String, Object>>) nativeQuery.getResultList();
r.stream().forEach(System.out::println);

Does anybody knows how can I print results in order?

Create this class and call it instead of: AliasToEntityMapResultTransformer.INSTANCE

public class MyTransformer extends AliasedTupleSubsetResultTransformer {

public static final MyTransformer INSTANCE = new MyTransformer();

/**
 * Disallow instantiation of AliasToEntityMapResultTransformer.
 */
private MyTransformer() {
}

@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
    Map result = new LinkedHashMap<>(tuple.length);

    for (int i = 0; i < tuple.length; i++) {
        String alias = aliases[i];
        if (alias != null) {
            result.put(alias, tuple[i]);
        }
    }
    return result;
}

@Override
public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
}

/**
 * Serialization hook for ensuring singleton uniqueing.
 *
 * @return The singleton instance : {@link #INSTANCE}
 */
private Object readResolve() {
    return INSTANCE;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM