1 package org.hibernate.exception; 3 4 import org.apache.commons.logging.Log; 5 import org.apache.commons.logging.LogFactory; 6 import org.hibernate.HibernateException; 7 import org.hibernate.JDBCException; 8 import org.hibernate.cfg.Environment; 9 import org.hibernate.dialect.Dialect; 10 import org.hibernate.util.ReflectHelper; 11 import org.hibernate.util.StringHelper; 12 13 import java.lang.reflect.Constructor ; 14 import java.sql.SQLException ; 15 import java.util.Properties ; 16 17 22 public class SQLExceptionConverterFactory { 23 24 private static final Log log = LogFactory.getLog( SQLExceptionConverterFactory.class ); 25 26 private SQLExceptionConverterFactory() { 27 } 29 30 43 public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException { 44 SQLExceptionConverter converter = null; 45 46 String converterClassName = ( String ) properties.get( Environment.SQL_EXCEPTION_CONVERTER ); 47 if ( StringHelper.isNotEmpty( converterClassName ) ) { 48 converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() ); 49 } 50 51 if ( converter == null ) { 52 log.trace( "Using dialect defined converter" ); 53 converter = dialect.buildSQLExceptionConverter(); 54 } 55 56 if ( converter instanceof Configurable ) { 57 try { 58 ( ( Configurable ) converter ).configure( properties ); 59 } 60 catch ( HibernateException e ) { 61 log.warn( "Unable to configure SQLExceptionConverter", e ); 62 throw e; 63 } 64 } 65 66 return converter; 67 } 68 69 75 public static SQLExceptionConverter buildMinimalSQLExceptionConverter() { 76 return new SQLExceptionConverter() { 77 public JDBCException convert(SQLException sqlException, String message, String sql) { 78 return new GenericJDBCException( message, sqlException, sql ); 79 } 80 }; 81 } 82 83 private static SQLExceptionConverter constructConverter(String converterClassName, ViolatedConstraintNameExtracter violatedConstraintNameExtracter) { 84 try { 85 log.trace( "Attempting to construct instance of specified SQLExceptionConverter [" + converterClassName + "]" ); 86 Class converterClass = ReflectHelper.classForName( converterClassName ); 87 88 Constructor [] ctors = converterClass.getDeclaredConstructors(); 90 for ( int i = 0; i < ctors.length; i++ ) { 91 if ( ctors[i].getParameterTypes() != null && ctors[i].getParameterTypes().length == 1 ) { 92 if ( ViolatedConstraintNameExtracter.class.isAssignableFrom( ctors[i].getParameterTypes()[0] ) ) { 93 try { 94 return ( SQLExceptionConverter ) 95 ctors[i].newInstance( new Object []{violatedConstraintNameExtracter} ); 96 } 97 catch ( Throwable t ) { 98 } 100 } 101 } 102 } 103 104 return ( SQLExceptionConverter ) converterClass.newInstance(); 106 107 } 108 catch ( Throwable t ) { 109 log.warn( "Unable to construct instance of specified SQLExceptionConverter", t ); 110 } 111 112 return null; 113 } 114 } 115 | Popular Tags |