java 在LinkedHashMap中强制转换HashMap

smdncfj3  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(670)

我正在将数据库中的结果导入到List<Map<String, Object>>中,问题是值的顺序不对,所以我想强制转换为LinkedHashMap,但是我遇到了这个异常:

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')

方法如下:

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);

有人知道如何按顺序打印结果吗?

t3psigkw

t3psigkw1#

创建此类并调用它,而不是:第一个月

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;
}
}

相关问题