java - How to get values out of JPA unique constraint violation? -


i'm doing web project primefaces sends , gets data remote ejb uses jpa. got code handle unique values, after setting unique=true in entity bean:

try{     emsave.persist(newitem); } catch (persistenceexception pe){     system.out.println("dupe found"); } 

then rollback transaction. in eclipse console these messages jboss as:

09:15:12,179 warn  [org.hibernate.engine.jdbc.spi.sqlexceptionhelper] (http-localhost-127.0.0.1-8189-6) sql error: 1062, sqlstate: 23000 09:15:12,179 error [org.hibernate.engine.jdbc.spi.sqlexceptionhelper] (http-localhost-127.0.0.1-8189-6) duplicate entry 'asdasd' key 'username' 

i have send objects can't saved front-end , display them in table, or mark them somehow in table user knows has change. have way how that, don't know how mark field has bad value. possible 'username' field filled incorrectly exception, or way should used? i'm looking elegant solution.

first of all, persist() not throw exception. persist() marks object persistent attaching persistence context. actual insert happen @ flush time.

second, seems want in loop. runtime exeptions irrecoverable , leave context in unreliable state. exception, current transaction should rollbacked , shouldn't keep using entity manager.

and finally, these 2 facts , common practices lead solution: shouldn't rely on exceptions detect incorrect values. if names should unique, should issue query test if entered names exist in table, , insert once have validated everything. of course, have race condition between 2 concurrent transaction, situation won't happen often, , can use generic "oops" error message handle (or retry transaction if necessary).


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -