001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.orm.hibernate4; 018 019import org.hibernate.HibernateException; 020 021import org.springframework.dao.DataAccessException; 022import org.springframework.dao.support.PersistenceExceptionTranslator; 023 024/** 025 * {@link PersistenceExceptionTranslator} capable of translating {@link HibernateException} 026 * instances to Spring's {@link DataAccessException} hierarchy. 027 * 028 * <p>Extended by {@link LocalSessionFactoryBean}, so there is no need to declare this 029 * translator in addition to a {@code LocalSessionFactoryBean}. 030 * 031 * <p>When configuring the container with {@code @Configuration} classes, a {@code @Bean} 032 * of this type must be registered manually. 033 * 034 * @author Juergen Hoeller 035 * @since 3.1 036 * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor 037 * @see SessionFactoryUtils#convertHibernateAccessException(HibernateException) 038 */ 039public class HibernateExceptionTranslator implements PersistenceExceptionTranslator { 040 041 @Override 042 public DataAccessException translateExceptionIfPossible(RuntimeException ex) { 043 if (ex instanceof HibernateException) { 044 return convertHibernateAccessException((HibernateException) ex); 045 } 046 return null; 047 } 048 049 /** 050 * Convert the given HibernateException to an appropriate exception from the 051 * {@code org.springframework.dao} hierarchy. 052 * @param ex HibernateException that occured 053 * @return a corresponding DataAccessException 054 * @see SessionFactoryUtils#convertHibernateAccessException 055 */ 056 protected DataAccessException convertHibernateAccessException(HibernateException ex) { 057 return SessionFactoryUtils.convertHibernateAccessException(ex); 058 } 059 060}