Forums Register Login

Simple Hibernate Example with Hashtable using Complex Key

+Pie Number of slices to send: Send
Hash Map Example With Complex Key

This is the simplest stand-alone example of a persistent hash map with a complex key in Hibernate that I could cook up.

When I first tried to learn about hash maps in Hibernate, I found many examples of a hash map using a simple key (meaning the key is just a single primitive data type or just a single string). For my needs, I need a hash map that uses a real-world key. I searched for days, and had other members of my development team search for days, of an example of this. I'm pretty sure there are no worked-out examples of a hash map with a complex key in Hibernate on the Internet. I think this is the first (and for now the only) example on any of the interwebs. That's why I posting this

Note to anybody that is creating Hibernate documentation: Nobody wants to learn Hibernate. We just want to get our data into and out of persistence. Just give us examples. We can pick apart an example faster than you can explain it.

Any hash map with a complex key requires at least three classes: The class in which the hash map is instantiated (the containing class), the class that is the hash map key (the key class), and the class that is the hash map values (the value class). That's why this "simple" example has so much code.

The requirements on the key class are:
  • It must be Embeddable
  • It must provide valid implementations of equals(...) and hashkey(). This is true for any class that wishes to be a key in a hash map.
  • It must implement java.io.Serializable
  • It must have a no-argument constructor. This is just like any other Hibernate object.


  • These are the requirements on the value class:
  • It must use an instance of the key class as its primary key
  • The primary key must be tagged EmbeddedId
  • It must have a no-argument constructor. This is just like any other Hibernate object.


  • These are the requirements on the containing class:
  • The hash map must be annotated OneToMany


  • Notice: This is provided with no warranty whatsoever. Use at your own risk.

    This is the key class:

    This is the value class:

    This is the containing class:

    This is an example of how to use it:
    When it is used for evil, then watch out! When it is used for good, then things are much nicer. Like this tiny ad:
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com


    reply
    reply
    This thread has been viewed 2491 times.
    Similar Threads
    Simple Hibernate Container Example
    Simple Hibernate POJO example
    Simple Hibernate Example with Final Classes and Final Methods
    Simple Hibernate Example with Inner Classes
    Simple Hibernate Cascade Save Example
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 28, 2024 11:12:55.