Here's how I handle it :
import org.springframework.dao.support.DataAccessUtils;
public Item getItemByName(String name) {
List results = getHibernateTemplate().find("from Item where name=?",
name);
return (Item) DataAccessUtils.uniqueResult(results);
}
The source of DataAccessUtils.uniqueResult is below. As you can see, it
returns null if the collection size is 0 and if the size is greater then 1,
it throws an exception as its an error condition.
public static Object uniqueResult(Collection results) throws
IncorrectResultSizeDataAccessException {
int size = (results != null ? results.size() : 0);
if (size == 0) {
return null;
}
if (!CollectionUtils.hasUniqueObject(results)) {
throw new IncorrectResultSizeDataAccessException(1, size);
}
return results.iterator().next();
}
On 12/11/06, Man-Chi Leung <[EMAIL PROTECTED]> wrote:
hi,
I would like to seek for advice on how u friends are handling a
situation whereby data is not found at Dao.
e.g. i have the following method in my ItemHibernateDao implementation:
public Item getItemByName(String name) {
List results = getHibernateTemplate().find("from Item where
name=?", name);
return (Item) results.get(0);
}
if NO data is found, very "nicely", spring will return a empty List
after find() . YES, it will crash my return "results.get(0) "
after reading a number of examples. I got the following choices:
1)at dao, check if results.isEmpty(), then throws
EmptyResultDataAccessException and catch at Service layer. rewrap with
my own new DataNotFoundException and pass it back to MVC
2)at dao, check if results.isEmpty(), then return a null back to
service layer, then throw new DataNotFoundException and pass to MVC
3)at dao, change the return signature to List, just throw empty list
back to service layer, check if empty throw new DataNotFoundException
to MVC
4)at dao, check if results.isEmpty(), then throw new
"DataNotFoundException" to service layer.
i am pretty confused here. should I need my own "DataNotFoundException"
at all? should I throw it at dao and catch at service layer? or throw
it at service and catch at MVC layer?
how about just rewrap and throw any spring exception (.e.g
DataAccessException or EmptyResultDataAccessException) all the way from
DAO level, (simply throw all DataAccessException at service), and
only catch at MVC layer ??
pls advice.
~thinkboy
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]