简体   繁体   中英

how to check if an item with same name exists using dao,hibernate

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);
}

Either is valid. Alex gives some other alternatives in his answer. If you're worried about performance, you usually don't need to. Write it the way that seems right. Optimize later, when it's proven to be needed. This code is very clean and easy to understand compared to how else it could be written:

if (dao.checkForExistence(something)) {
    return duplicateSomethingResponse();
}
dao.makePersistent(something);

You can do conditional update with where name=? and if number of updated rows is 0 do insert. And if you make name a key, Hibernate will take care of it for you with saveOrUpdate . Anyway, name, probably, should be indexed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM