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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It looks like, it would be good solution. Can you explain the part of Reflection and override the authusertoken?
@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.
when i use this solution. It gives me error that says UUID is not applicable for arguments int?
Also using private UUID authusertoken = UUID.randomUUID().toString(); solves storing string problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.