jquery

gist JS

Tuesday, January 16, 2007

Hibernate NonUniqueExceptions

So I knew I was in trouble this morning when I googled "hibernate nonuniqueidentifier" and only came up with references to my own blog. That's happened once before and it's never a good thing to find out that google believes you're the world expert on the very thing you're having a problem with.

Anyway here was the solution to my Hibernate NonUniqueException. I hadn't had any problems until I made the entire service layer transactional with some a little AOP magic, but once I did that all updates started throwing these NonUniqueExceptions.

Here's the code w/ the addition of:
getHibernateTemplate().evict(sameNamed);

to prevent the Exception. Basically Hibernate is just trying to protect me from updating over myself, but since I really do want to just read properties of "sameNamed" Topic and then write over it, eviction is just fine.


public Topic save(Topic t) throws BusinessException {

if(t.getTitle().equals("")){
throw new BusinessException("Empty Title");
}
if(t.mustHaveUniqueName()){
Object[] args = {t.getTitle(),t.getUser()};
Topic sameNamed = (Topic) DataAccessUtils.uniqueResult(getHibernateTemplate().find("from Topic where title = ? and user = ?",args));

if(sameNamed != null && sameNamed.getId() != t.getId()){
throw new BusinessException("Duplicate Name");
}
//need to evict or we'll get a NonUniqueException
getHibernateTemplate().evict(sameNamed);
}
getHibernateTemplate().saveOrUpdate(t);
}

1 comment:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!