views:

25

answers:

1

Hi, I am using Spring + Hibernate to create and store a record in a MySQL database.

Just before persisting a record I want my system to generate a random-string which will be stored in a field in the entity that is being stored. This random-string of characters will be used later as an access-key to retreive the record and confirm the user's input.

I thought of using a method in my entity class annotated with @PrePersist to realize this behaviour. Is this the proper place to put such a method?

This question occured to me as I would not know how to check the database table for the uniqueness of the random-string as I cannot think of a way to reference the spring's HibernateTemplate instance to do a query from within the entity class.

Any suggestion is much appreciated.

A: 

Just before persisting a record I want my system to generate a random-string which will be stored in a field in the entity that is being stored.

A PrePersist life cycle callback method would be indeed perfect for this use case.

This question occured to me as I would not know how to check the database table for the uniqueness of the random-string as I cannot think of a way to reference the spring's HibernateTemplate instance to do a query from within the entity class.

HibernateTemplate / JpaTemplate or not, there is actually no way to check the uniqueness of a value using a SQL query (at least not in a 100% deterministic way) without locking the whole table and you probably don't want that. Without a lock on the whole table, you can face a race condition: while a thread T1 would perform a select, a thread T2 could insert the value that T1 didn't find and commit first, causing the failure of a subsequent insert from T1.

In other words, the only way to guarantee the uniqueness or a column is to insert the record and commit the transaction (a database could use deferred constraint checks so the commit is required).

Pascal Thivent
Thanks for your thoughts. Indeed I do not want to lock the table. So if I understand you correctly, I would need to try to persist the record and let for example the database check for uniqueness of the field-value in the column and catch the error that the database might throw. Is that correct?
Baris
@Baris Yes, that's exactly it.
Pascal Thivent