Reputation: 2125
I have entity Foo
, which maps to sql table with some unique constraints. Thus saving Foo
may fail. I am using FooDao
to save Foo
:
@Repository
public class FooDao
{
@Autowired
private SessionFactory sessionFactory;
@Transactional
@Override
public void add(Foo item) {
sessionFactory.save(item);
}
}
when I call method FooDao#add(Foo)
it may fail for two reasons: either because of unique constraint violation (in this case, I know how to handle the problem) or because of some other problem (in this I probably should propagate the exception). How do I distinguish between those two situations?
I could add method find(Foo item)
to FooDao
and check, whether something like item, which I was trying to add is database. But this would require additional select from database and I am a bit worried about this.
Upvotes: 0
Views: 542
Reputation: 3373
If there is a database exception it gets caught in a HibernateException, which is a checked exception. Spring
wraps this in a DataAccessException, which is unchecked. This exception will run up to your Controller
and out to the Servlet
and end up in a stack trace in the browser and log file. You can catch this exception and print it out so you can see what is happening. This will at least get you to the point where you know what is actually breaking.
Bad keys is probably one issue. But bad values is probably another. Some non-null fields are null, or something isn't long/short enough etc. Fixing this probably involves validation. You can use the Hibernate Validator. You give your fields some nifty annotations and then you get validation errors in java before you even get to the database - errors happen faster.
Upvotes: 0
Reputation: 923
Thats actually SQLState.
do something like this
Catch(HibernateException he){
SQLException sqe = he.getSQLEception();
String sqlState = sqe.getSQLState();
if(sqlState.equals("23000"){
// Handle your exception
}
}
Java doc: SQLState - an XOPEN or SQL:2003 code identifying the exception
One link I found for ISO sqlStates,
But look for exact reference and value..
Upvotes: 1
Reputation: 923
Catch org.hibernate.JDBCException. This has getErrorCode(). For unique constraint voilation its ORA-00001.
-Maddy
Upvotes: 0
Reputation: 3860
One obvious (but maybe nasty) solution is that you catch javax.persistence.PersistenceException and parse the error message for "violant" or "constraint".
From my point of view you should do the select/find upfront. Remember that you are using an ORM! Hibernate has caches involved so neither the select/find nor the key contraint error might be the result of an actual db query but the result of an calculation of Hibernate based on your already in cache loaded data.
Sebastian
Upvotes: 0