VB_
VB_

Reputation: 45692

Get ID before saving to database

I use hibernate sequences to generate id of an entity. I use PostgreSQL 9.1.

Is it possible to get entity id before it is saved to database? How?

Upvotes: 6

Views: 10818

Answers (3)

K.C.
K.C.

Reputation: 2112

You can implement the interface org.hibernate.id.IdentifierGenerator and create a Id generator.

Example:

import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;

public class TimeBasedIDGenerator implements IdentifierGenerator {

    private static TimeBasedGenerator generator = Generators.timeBasedGenerator();

    private static TimeBasedIDGenerator SINGLETON = new TimeBasedIDGenerator();

    public static UUID generate() {
        return SINGLETON.generateUUID();
    }

    @Override
    public Serializable generate(SessionImplementor session, Object parent) throws HibernateException {
        return generator.generate();;
    }
}

This can be used in your Entities like this. So the id is generated by the constructor:

@Entity
public EntityClassName {

     private UUID uuid;
     private Integer mandatoryField;

    public EntityClassName() {
    }

    public EntityClassName(Integer mandatoryField) {
        this.uuid = TimeBasedIDGenerator.generate();
         this.mandatoryField = mandatoryField;
    }


    @Id
    @Column(name = COLUMN_XXX_UUID)
    @Type(type = "java.util.UUID")
    public UUID getUuid() {
        return uuid;
    }

    // setter + other properties

}

Upvotes: 0

Dariusz
Dariusz

Reputation: 22241

You explicitely create a separate sequence, get its value, then insert an object with id based on that value. You will have more code, but the ID will be available before the insertion and the guarantees for sequences are exactly the same as for serially given IDs, because they are essentially the same.

In other words:

  • create your own sequence
  • make a primary key a simple int not serial
  • get a number from sequence
  • use it as an ID for your object

This question has an answer saying how to get next sequence value.

Upvotes: 4

Vijay
Vijay

Reputation: 313

save() method returns the id of the entity that is saved. You can use it!

reference:-> http://docs.jboss.org/hibernate/annotations/3.5/api/org/hibernate/Session.html

Upvotes: 2

Related Questions