Hi all,
I'm facing the problem that my custom DAO object (derived from HibernateDaoSupport) breaks after a DataIntegrityViolationException was thrown.
I've a MySQL table with 2 different unique keys (email and username must be unique in that table). When I'm trying to insert a new entity in that table and one of the attributes violates an unique key constraint, a DataIntegrityViolationException is thrown. After that exception I like to figure out what was the reason (either a duplicated key on column "username" or "email" or on both columns), but my HibernateDaoSupport object seems to be broken then:
I'm using Hibernate 3.1.3 on a multitheaded spring-based webservice. I assume that the session handling is "thread-bound". What is the common way to distinguish what was the reason for that exception? I really don't like to parse the MySQL error string.
Code:
try {
final Entity entity = new Entity();
entity.setUserName(username);
entity.setEmail(email);
dao.persist(entity); // fails on duplicated key violation
} catch (DataIntegrityViolationException e) {
// trying to figure out if there is an existing entity with the given email or username to return the right error message.
// that call also fails because getHibernateTemplate() returns null then... so I can't submit a new query.
if (dao.getByEmail(email) != null) {
throw new DuplicateEmailException(email);
}
// that call also fails because getHibernateTemplate() returns null then... so I can't submit a new query.
if (dao.getByUsername(username) != null) {
throw new DuplicateUsernameException(username);
}
}