mysql - Database - handling of unique constraint violation -
i have user creation screen takes various user details along first name , mobile number. have corresponding user table in first name , mobile number form composite unique key. there other integrity constraints defined on table well.
when user data entered on create user screen violates constraint, user needs shown 'user friendly' error message.
when such violation occurs, exception mysql database is:
com.mysql.jdbc.exceptions.jdbc4.mysqlintegrityconstraintviolationexception: duplicate entry '1-1' key `uk_first_name__mobile_idx`
there 2 options show meaningful message (for example: "error: user name exists given mobile number, please change either 1 of them").
option 1: in catch block of exception, parse mysql exception's message , 'uk_first_name__mobile_idx'. if present, show user friendly message mentioned above.
option 2: write dao level api take first name , mobile number 2 parameters, fire database query see if there existing record matching first name/mobile combination. if true, show error message user; else, run insert query insert user of record user table.
i not option 1, needs me 'parse' exception message, not clean solution. not option 2 well, needs me run 'two queries' on database less efficient option 1, single query solution.
question: there other options better these two? if not, 1 right approach among above two?
i think "option 2" (manually checking constraint before attempting insert) horrible, not because of race hazard (which avoided locking reads), (as note) because of additional load on database: after all, manually check constraints negates purpose , benefit of using constraints within database.
i agree parsing error message strings feels "dirty", strings well defined. 1 refer underlying errmsg.txt
or source header files.
once 1 has extracted key name error message, 1 can use key_column_usage
information schema identify offending columns:
public static final int er_dup_entry = 1062; public static final int er_dup_entry_with_key_name = 1586; public static final string regex_dup_entry_with_key_name = "duplicate entry '(.*)' key '(.*)'"; // ... try { // ... } catch (mysqlintegrityconstraintviolationexception e) { switch (e.geterrorcode()) { case er_dup_entry: case er_dup_entry_with_key_name: pattern p = pattern.compile(regex_dup_entry_with_key_name); matcher m = p.matcher(e.getmessage()); sqlquery query = session.createsqlquery( " select column_name" + " information_schema.key_column_usage" + " constraint_schema = :schema" + " , constraint_name = :key" ); query.setstring("schema", "my_schema"); query.setstring("key" , m.group(2)); showduplicateerror(query.list()); break; } }
Comments
Post a Comment