0

I have an object so that

class MyObj{
    public long id_1;
    ... 
}

My HBM (hibernate mapping file) tells that this id_1 is my Id. Now what i want to do is to cache this entity in HashMap so that HashMap<MyObj, NestObj> i.e., MyObj will become the key for the hashMap.

Now the question that I wanted to ask

I want to make sure that even though i have saved the whole object as the key, I want to keep object retrieval/storing in the hashmap based on the MyObj.id_1 value. The easiest way i can do so is to after retrieving all objects, I have to do a for loop to add them in a map as Map <Integer, MyObj> but in that case i would have maintain two maps (one for MyObj and other for NestedObj) which i want to avoid.

How can i dictate my HashMap to use MyObj.id_1 column to use as comparator, hash etc. Shall i override hash and equal function ? But if i do so, would it affect hibnerate comparison while storing/retrieving entities ?

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • If you want to lookup the map using id_1. Why not store that as the key and save MyObj and NestObj as a compound value (you can choose your data structure) ? For example HashMap>. I assume you need other attributes of MyObj once you look it up. – uncaught_exception Feb 02 '16 at 15:49
  • Yup, thats another approach. But i wanted to take this problem as an opportunity to understand more how can i leverage existing object hash/equal methods used by java collection. – Em Ae Feb 02 '16 at 15:51
  • Your question suggests you already know that. The only issue is how it would affect Hibernate. Check this out for that http://stackoverflow.com/questions/1638723/equals-and-hashcode-in-hibernate. I don't know your problem domain but I would never override equals and hashcode based on one use case of hashing requirement. – uncaught_exception Feb 02 '16 at 15:55
  • With reference to @ShireResident's comment, you probably don't need a `Map` as the value but just a `Pair`. `HashMap` uses the key's natural `equals` and `hashCode` but you can trivially wrap it in another class that uses `MyObj.id_` for both – Miserable Variable Feb 02 '16 at 15:55
  • 1
    is it any good reason why you don't want to use build in caching mechanism? – user902383 Feb 02 '16 at 16:17
  • I am new to spring, don't know anything about it. so i am trying to figure out what options are better. As long as built-in mechanism doesn't require extra configuration, imight be okay with it. Can you give me some pointers on that ? – Em Ae Feb 02 '16 at 16:27

0 Answers0