Batmat is right about using uniqueResult() if the name column is unique for the item table. But, I'm going to have to disagree with the exception advice. :)
You only want to throw exceptions for programatic off normal states. I would not consider a user mistyping a string into an edit box a programatic off normal state. Do yourself a favor and return null. You really don't want to be propogating exceptions through your layers, it just makes a mess of things later and essentially forces you to generate a whole exception hierarchy. If you really want to create a proper exception hierarchy, then knock yourself out, but that will involve DaoException as an abstract Exception, specific DataNotFoundException subclassed from DaoException, trapping the generic DaoException in the service layer and handling specific subclasses. And then what? Rethrow a ServiceException and pass it up the chain to the presentation layer? Which code is cleaner?
Code:
// DAO
public Item getItemByName(String name) {
return result = (Item) getHibernateTemplate().find("from Item where name=?", name).uniqueResult();
}
// SERVICE
...
Item item = getItemByName("joeschmoe");
return item == null ? "No data found" : item.toString(); // or whatever the service layer returns
...
or
Code:
// DAO
public Item getItemByName(String name) throws DaoException {
Item result = (Item) getHibernateTemplate().find("from Item where name=?", name).uniqueResult();
if (result == null) {
throw new DataNotFoundException("No item was found for " + name);
} else {
return result
}
}
// SERVICE
...
try {
Item item = getItemByName("joeschmoe");
return item.toString(); // or whatever the service layer returns
} catch DaoException {
return "No data found";
}
...
DAOEXCEPTION
public abstract class DaoException extends Exception {
...
}
DATANOTFOUNDEXCEPTION
public class DataNotFoundException extends DaoException {
...
}
Every time I've tried to generate an exception hierarchies for non-programatic off normal states, it turned out to be a huge pain in the rear, with an exception hierarchy that matches or exceeds the complexity of the layered architecture! Just let your service layer transform the result into something the presentation can display and be on your merry way. I mean, the uniqueResult() method returns null if the data is not found, that should be a clue as to what the Hibernate developers think about throwing an exception in that instance. :D