Is there a less expensive method to do the following primary key validation in hibernate
I need to make sure the new supplierpart I'm creating doesn't exist开发者_运维百科. It is currently done like so
try {
entityManager.get(SupplierPartEntity.class,
new SupplierPartPK(supplierID, partID));
throw new CreateSupplierPartActionException("Supplier part record exists for " + supplierID
+ " / " + partID + ".");
} catch (final RecordNotFoundException e) {
/* supplier part not found - do nothing */
}
its worth noting entityManager will throw a record not found exception when get() would normally return null;
If by "less expensive" you mean "doesn't hit the database", then no, unless you keep a cache in memory of all existing primary keys. Other than that, the database is the only thing that knows them.
It looks like you're using the SupplierID and Part ID as a primary key to enforce uniqueness?
Why not go ahead and try to create the new record and catch the uniqueness constraint violation when/if it happens? (Sorry, that item already exists)
精彩评论