Hibernate MulitpleTableGenerator

This key generator is designed to enable Hibernate to generate unique keys using the table structure like this one

The keys that you get from database can be used directly or with HiLo algorithm (use MultipleTableHiLoGenerator class in that case).

Usage

If you want to generate keys for your objects with this generator, just change <id> section in appropriate hbm.xml file to something like this.

<id name="id" type="long" column="cat_id">
        <generator class="net.nighttale.hibernate.MultipleTableGenerator">

                <param name="table">keys</param>
                <param name="column_name">key</param>
                <param name="column_value">next_value</param>
                <param name="counter_name">ids</param>

        </generator>
</id>

Default parameter values are

table=hibernate_unique_keys
column_name=name
column_value=value
counter_name=default

and if you want to use some of them, you can left that <param> tag out of the configuration.

In order to use this key generator, you’ll have to generate appropriate table with following DDL

CREATE TABLE hibernate_unique_keys (
	name VARCHAR(255) NOT NULL,
	value INTEGER,
	PRIMARY KEY(name)
)

or let the Hibernate do it by setting Environment.HBM2DDL_AUTO property to create value.

Installation

Installation is easy, just download the source code from here, unzip it and put it somewhere in your classpath.

Leave a comment

Your email address will not be published. Required fields are marked *