简体   繁体   English

Hibernate-将hql查询映射到HashMap <String, String>

[英]Hibernate - Mapping a hql query to a HashMap<String, String>

I've already looked at the post here: 我已经看过这里的帖子:

With Hibernate, how can I query a table and return a hashmap with key value pair id>name? 使用Hibernate,如何查询表并返回键值对id> name的hashmap?

And that has a beautiful answer, but what if I want the key of my HashMap to be a String with spaces? 答案很漂亮,但是如果我希望HashMap的键是带空格的String怎么办? Or other characters for that matter? 还是其他角色呢?

This will work fine...think about how a HashMap works...it's backed by a hash table. 这将很好地工作...考虑HashMap工作原理...它由哈希表支持。 If you have some String , we'll call it key , then by the Java specification the hashCode() method of any object has to be deterministic, ie return the same hash code value when called on an object for the life of the instance of the JVM it's running in. 如果您有一些String ,我们将其称为key ,那么根据Java规范,任何对象的hashCode()方法都必须是确定性的,即在对象的整个生命周期内调用对象时返回相同的哈希码值运行它的JVM。

Spaces will not affect the hash code of a String object. 空格不会影响String对象的哈希码。 Adding spaces to a string will make it a different String and therefore result in a different hash code. 在字符串中添加空格使它成为不同的String ,从而导致产生不同的哈希码。 See for yourself: 你自己看:

public static void main(String[] args) {
    Map<String, String> someMap = new HashMap<String, String>();

    someMap.put("some random key", "value");

    System.out.println(someMap.get("some random key"));
    System.out.println(" some random key ".hashCode()); // prints 1846300114
    System.out.println("some random key".hashCode()); // prints -2030143442

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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