Greetings,
All my data tables in my database have a BIGINT field named "id" as their pk.
NONE of them use the AUTO_INCREMENT feature - instead I have a table named
Used_Random_Longs consisting of fields:
--- random_long BIGINT(12) unsigned PRIMARY KEY,
--- used_in_table varchar(30)
Inserting a row into a data table consists of:
a--using a stored procedure to generate random BIGINTs until one
successfully INSERTs into UsedRandomLongs then returning
successfulbigintb--insert the desired data into a new row of the data table then perform an
UPDATE UsedRandomLongs
SET used_in_table =
datatablename WHERE id =
successfulbigintThus I can guarantee every id is unique across the database and know at a glance which table it's used in.
Now I'd like to build a custom identity generator to achieve the same thing.
So far I've got this
Code:
package dogs.model;
import org.hibernate.*;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.sql.*;
import utils.*;
import static org.hibernate.criterion.Expression.*;
import java.util.*;
public class UniqueLongIdGenerator implements IdentifierGenerator
{
public Serializable generate(SessionImplementor session, Object object) throws HibernateException
{
Long out_llng = -1L;
UsedRandomLongs uri = null;
Random rand_generator = new Random();
do {
out_llng = rand_generator.nextLong() & 0xE8D4A50FFF; // masks to 0 - 999999999999
uri = new UsedRandomLongs();
} while ( !session.save( uri, out_llng;
return out_llng;
}
}
and
Code:
package dogs.model;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.Query;
import org.hibernate.context.ManagedSessionContext;
import javax.persistence.*;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import utils.*;
import java.util.Arrays;
@Entity
@Table(name="Used_Random_Longs")
public class UsedRandomLongs
{
@Id
@Column(name="random_long")
private Long id;
private String used_in_table;
//constructor
UsedRandomLongs() {
this.used_in_table = "pending";
}
........
and one class that's been mapped to a data table
Code:
package dogs.model;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.Query;
import org.hibernate.context.ManagedSessionContext;
import javax.persistence.*;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import utils.*;
import java.util.Arrays;
@Entity
@Table(name="Frogs")
public class Frogs
{
@Id
@GeneratedValue(generator="UniqueLongIdGenerator")
@Column(name="random_integer")
private Long id;
........
Any help/hints/suggestions/constructive criticisms and examples are all appreciated!
Still-learning Steve