java - Do I need to call JPA flush to check database constraints when my application is clustered? -
i read jpa caches sql instructions improve performance:
jpa providers hibernate can cache sql instructions supposed send database, until commit transaction. example, call em.persist(), hibernate remembers has make database insert, not execute instruction until commit transaction.
i have java ee 6 application deployed glassfish cluster 2 instances. in application there race condition 2 singletons expensive queries , cache results in database table. they're doing same work , trying write same record, exception:
java.sql.sqlintegrityconstraintviolationexception: ora-00001: unique constraint (someschema.sometable_pk) violated
i decided easiest way deal catch , ignore exception:
// in ejb container-managed transactions. public entity getexpensiveentity(int entityid) { entity entity = entitymanager.find(entity.class, entityid); if (entity == null) { try { result = expensivequeries(); entitymanager.persist(result); entitymanager.flush(); } catch (sqlintegrityconstraintviolationexception ex) { // other instance created result, it. result = jpa.find(result.getid()); } } return result; }
i think call flush
necessary because otherwise sqlintegrityconstraintviolationexception won't occur until transaction ends somewhere ejb call stack, past catching , ignoring. correct, valid use case flush
? there better way handle this?
reference
Comments
Post a Comment