John
John

Reputation:

How to get auto generated field before save in hibernate

I am using this in my pojo

@Column(name = "uuid")
public String getUuid() {
    return UUID.randomUUID().toString();
}

Now i have not binded this in jsp form.

Now the problem is i have to send this uuid in the email , when the user fills the form.

But can i get that because in my opinion

1)First i have to save the user detail in database

Session session = sessionFactory.getCurrentSession();
      session.save(person);

Now it means i have to again query the databse get the id of person and then get the generated id. won't it waste resources of again querying database.

any easy solution

Upvotes: 0

Views: 2488

Answers (2)

Ken Chan
Ken Chan

Reputation: 90477

As you are using property access , hibernate will call getters of all the mapped properties of your user entity during the flushing process to determine if any values are changed .If there are values changes ,hibernate will then generate the corresponding UPDATE SQL for the changes properties. As your getUuid() always return a new random value , hibernate will always detect this change and always update the value of the uuid column to a new value whenever you update the user entity .

The uuid sent to user by email is then not correct anymore . So , I think your uuid should at least be read-only and should be generated automatically when a user instance is created. You can achieve it by assiging the value of uuid in the constructor of the user , like this :

public class User {

        .......
        private String uuid;
        ......

        public User() {
                this.uuid = UUID.randomUUID().toString();
        }

        public String getUuid() {
                return uuid;
        }

        private void setUuid(String uuid) {
                this.uuid = uuid;
        }

}

You can then call user.getUuid() to get the generated id after user is instantiated.

Upvotes: 0

WhiteFang34
WhiteFang34

Reputation: 72049

Can't you pass the UUID to whatever generates the email or store it temporarily with a session attribute?

Upvotes: 1

Related Questions