Reputation: 16646
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.
Upvotes: 0
Views: 1608
Reputation: 378
I use this to generate primary key :java.util.UUID.randomUUID().toString().replaceAll("-", "");
It will generate 32-digit primary key like this:1b694a70285f49c8a25a5de598042e7b .
It has little chance to get duplicate primary key by using this approach.
It would be nice to use this with hibernate GeneratedValue. sample code would like be :
@GeneratedValue(generator="UUIdentifier")
@GenericGenerator(name="UUIdentifier", strategy = "uuid")
private String resourceId;
uuid set by to strategy is provided by Hibernate, you can feel like to use your own Java class by set strategy using qualified name of your own class.
Upvotes: 0
Reputation: 13779
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.
Upvotes: 0
Reputation: 28059
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.
Upvotes: 1