2

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;
    }

}
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Ali Arda Orhan
  • 764
  • 2
  • 9
  • 24

1 Answers1

1

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.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • It looks like, it would be good solution. Can you explain the part of **Reflection and override the authusertoken?** – Ali Arda Orhan Aug 07 '14 at 11:15
  • @user3137442, I guess @VladMihalcea wants to say that if an object already have value of `authusertoken` in DB then at the time of fetching Hibernate will override the DB value to `authusertoken`. – Amogh Aug 07 '14 at 11:24
  • when i use this solution. It gives me error that says UUID is not applicable for arguments int? – Ali Arda Orhan Aug 07 '14 at 11:59
  • Also using **private UUID authusertoken = UUID.randomUUID().toString();** solves storing string problem. – Ali Arda Orhan Aug 07 '14 at 12:11