John
John

Reputation:

How to bind uuid field with spring mvc and hibernate

I have entity class which is annotated with hibernate and MySQL. I want to generate a UUID and insert it in the user table.

  1. How can I map that field with hibernate?

  2. How to bind that field with spring mvc and jsp because that field will be autogenerated and won't be in the user form?

Upvotes: 0

Views: 1716

Answers (2)

user638455
user638455

Reputation:

It's been a while since I wrote any Hibernate but I'm fairly sure you can just initialise it on construction and the id will be written to the DB on save and loaded from the db on load. You may find that a random UUID is less performant than the standard long primary key.

class MyEntity {

    @Id
    private String id = UUID.randomUUID().toString();

Upvotes: 2

matt b
matt b

Reputation: 140041

Well, you shouldn't bind any fields in your Form object that the user isn't actually filling out in the HTML form. Just let the DAO and backend classes deal with populating any sort of auto-generated ID.

As for generating a UUID with Hibernate, you can use Hibernate's built-in uuid generator or one of several other built-in generators, or you can use whatever type of unique ID generation logic is built into your Database Engine and just mark the ID field with <generator class="select"/> to have Hibernate query the database after inserting the row to find out the database-generated ID.

Upvotes: 0

Related Questions