Reputation: 139
String nativeSql = "Some random non-sql stuff";
Session sess = sessionFactory.openSession();
List <?> result = sess.createSQLQuery(nativeSql).list();
In case, if nativeSql request isn't a valid one, how do I catch a native exception (ex: PSQLException)?
Upvotes: 1
Views: 750
Reputation: 5451
If you check the docs for the Query.list()
method you'll see that it throws HibernateException
. If you check the docs for HibernateException
you'll see that all SQLExceptions will be wrapped in some form of JDBCException.
JDBCException
is a subclass of HibernateException
(that's from the docs too). So you can either catch HibernateException
, or JDBCException
if you want to be more specific.
If you then look at the docs for JDBCException
you'll find a method called getSQLException
which returns the underlying SQLException
. If you look at the docs for PSQLException
you'll see that it extends SQLException
.
Upvotes: 1
Reputation: 3059
Hibernate will wrap any SQLExceptions into a org.hibernate.JDBCException
. So you want to catch this Exception type. If you explicitly need to access an actual PSQLException, you can retrieve it through the getSQLException()
Method:
try {
String nativeSql = "Some random non-sql stuff";
Session sess = sessionFactory.openSession();
List <?> result = sess.createSQLQuery(nativeSql).list();
} catch (JDBCException e) {
SQLException sqlException = e.getSQLException;
if (sqlException instanceof PSQLException) {
PSQLException psqlException = (PSQLException) sqlException;
// ... work with psqlException ...
}
}
Upvotes: 3
Reputation: 122008
AFAIK , we cannot catch SQL native exception.
You might want to catch JDBCException which
Wraps an SQLException. Indicates that an exception occurred during a JDBC call.
Upvotes: 0