Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checks for constraint violation before persisting an entity

What is the best mechanism for preventing constraint violation checks before creation | modification of an entity?

Suppose if the 'User' entity has 'loginid' as the unique constraint, would it be wise to check if there is an user entry already with this loginid name before creation or modification.

OR

Would you let the database throw an ConstraintViolationException and handle this message appropriately in the UI layer. Where should such checks be enforced in the jboss seam framework.

Note: Currently no such checks are enforced on the seam-gen code.

We currently use Seam 2.2, Richfaces with Hibernate.

like image 343
Joe Avatar asked Jan 30 '10 11:01

Joe


People also ask

What does constraint violation mean?

A constraint violation is simply a grammatical error or a value that does not adhere to the LDAP schema. For example , you may be creating a user and providing characters that are not allowed for an attribute. Example: The telephone number attribute has schema that allows only numbers.

How do you handle unique constraint exception in Java?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result.


1 Answers

Even if you check the condition in your code before persisting the user object there is always a chance that someone will created a duplicate loginid between the time you check and when you persist the new User.

However it'll be easier to display an appropriate error message in the UI if you do an explicit check. If you have multiple contraints on the table catching the ConstraintViolationException won't allow you to easily determine which constraint has been violated.

So I would do both. Assuming you're extending from Seam's EntityHome:

  1. In the persist() method run a query to ensure that the loginid is unique. If it isn't add an error message to the appropriate control and return null.
  2. Wrap the call to super.persist() and catch the ConstraintViolationException, displaying a generic duplicate error message

EDIT

As Shervin mentioned creating a JSF Validator is a great idea (replacing) #1 above, but you should still expect the worst and catch ConstraintViolationException.

like image 142
mtpettyp Avatar answered Oct 23 '22 02:10

mtpettyp