views:

42

answers:

2

Hi,

I am using Java and Hibernate as ORM tool. Is there any way i can implement sequence in Java using Hibernate?

Currently I am using Oracle sequences to achieve this, but that is a very costly way as interaction with database increases.

Please help.

A: 

It is actually a very easy thing to do:

package mypackage;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.HibernateException;

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.UUID;

public class RandomIdentifierGenerator implements IdentifierGenerator {

  private final static SecureRandom sr = new SecureRandom();

  public Serializable generate(SessionImplementor sessionImplementor, Object o) throws HibernateException {
    long val = sr.nextLong();
    return Long.toString(Math.abs(val), Character.MAX_RADIX);
  }
}

IdentitfierGenerator is the hibernate interface you have to implement. The above example just generates a random id.

In order to use this you have to set the generator to mypackage.RandomIdentifierGenerator

Obviously this implementation lacks any guarantee of not generating the same id twice, this may or may not be important for the application you are writing.

Gareth Davis
A non-atomic sequence generator isn't a sequence in the database sense.
Tony Ennis
A: 

Currently I am using Oracle sequences to achieve this, but that is a very costly way as interaction with database increases.

Are you sure that using Oracle sequences is costly? As other commenters have mentioned, this is unlikely. Having said that, you should try to use sequences that increment by more than 1. Using such sequences along with hi-lo or pooled optimizers, is likely to work well. This ensures that a Hibernate Session will hit the database only once in N inserts, if N is the increment size of the sequence. The downside is that you will have to use a separate create_time column to identify the order of insertion of rows.

binil