Search code examples
javadatabasehibernatejpahibernate-mapping

Hibernate insert automatic number in a column


Hello brothers and sisters,

I have a class that keeps userAuthInformatin with authuserid column,username column, and authusertoken column.

I want to insert uuid number in authusertoken column with every insert. I learned about Generated(GenerationTime.INSERT) but i don't know exact way to do this.

package entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

@Entity
@Table(name = "authusers")
public class AuthUser {

    @Id
    @GeneratedValue
    private int authuserid;
    @Generated(GenerationTime.INSERT)
    @Column(name = "authusertoken")
    private long authusertoken;
    @Column(name = "username")
    private String username;

    public int getAuthuserid() {
        return authuserid;
    }

    public void setAuthuserid(int authuserid) {
        this.authuserid = authuserid;
    }

    public long getAuthusertoken() {
        return authusertoken;
    }

    public void setAuthusertoken(long authusertoken) {
        this.authusertoken = authusertoken;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

Solution

  • You can simply use the UUID Java class and assign a value to this token field at object creation time:

    @Column(name = "authusertoken", columnDefinition = "BINARY(16)")
    private UUID authusertoken = UUID.randomUUID();
    

    If the current associated row already has a value, when fetching the Entity, Hibernate will set it using Reflection and override the authusertoken with the row's column value.

    If this is a new object, the authusertoken will get a default UUID when the object is instantiated.