Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Overwriting equals, hashcode and serialisation in Java data access object

Options
  • 15-08-2008 6:32pm
    #1
    Registered Users Posts: 5,618 ✭✭✭


    I'm working on base level design of a set of large data transfer objects, with some logic that sits on top of them. These business objects are used in a large JEE multi-server environment, must be instantiable from web services, and must be serialisable to both Hibernate and a hierarchical TPF mainframe DB.

    The TPF requires that the serialisable components have a unique ID, and ideally, one would use this ID for the equality of objects, make it final and overwrite equals and hashcode accordingly. However, serialisation to hibernate requires that the objects also have a 0-parameter constructor. Since the IDs are in the context of a session, and at creation time you may not have access to this session, auto-assigning IDs for hibernate in the constructor doesn't work :(

    So, at the moment, I have IDs that are settable. But the problem here is that people actually set them sometimes. In particular, they set them after they've added them to a hashmap, and then when they call contains on that map, they get the wrong answer because the object they're looking for is in a different bucket to what the collection expects. And to be honest, contains is one of those methods that should just work, so I sympathise with this.

    The obvious next answer would be to compare memory addresses, but in a distributed environment, this doesn't always return the right results either.

    So, the perfect hack is
    public int hashCode(){
        return 0;
    }
    
    but at the end of they day, this is ugly and slow, and reduces the performance of hash-based systems to that of a list. I have an idea for a permanent solution but am curious to see what other suggestions you guys have...


Advertisement