In a web app,I am letting the user create an Item.The db manipulations are done through dao implementations which use hibernate.The generic dao implementation uses Criteria for the query
The name of an Item is unique.So,I have to prevent a user from creating two items with the same name. How should I do this in the code?Each time a user attempts to create an item,should I call itemDao.findItemByName(newname), and if an item exists, give the user an error message?Or should I put the item creation code in a try catch block,catch exception, and tell the user,the attempt to create a new item failed?
It seems to me ,the first approach will let me give a more precise error message to the user.But it will involve one db check call for every attempt to create item.The second will be some exception boiling up from the dao class and less specific.
I would appreciate some advice on this..
sincerely
Jim
GenericDaoImpl
...
public T findUniqueItemByProperty(String propName,String propVal){
Class clz = getPersistentClass();
Session session = getSession();
logger.info("session="+session.hashCode());
Criteria cri = session.createCriteria(clz).add(Restrictions.eq(propName,propVal));
return (T)cri.uniqueResult();
}
public void saveOrUpdate(T obj) {
getSession().saveOrUpdate(obj);
}
...
ItemDao
...
public Item findItemByName(String name){
return findUniqueItemByProperty("name",name);
}
public void saveOrUpdateItem(Item item){
saveOrUpdate(item);
}