1 package org.hibernate.util; 3 4 import java.lang.reflect.InvocationTargetException ; 5 import java.lang.reflect.Method ; 6 import java.sql.Connection ; 7 import java.sql.PreparedStatement ; 8 import java.sql.ResultSet ; 9 import java.sql.SQLException ; 10 import java.sql.Statement ; 11 12 import org.hibernate.AssertionFailure; 13 14 17 public final class GetGeneratedKeysHelper { 18 19 private GetGeneratedKeysHelper() {} 20 21 private static final int RETURN_GENERATED_KEYS; 22 private static final Method PREPARE_STATEMENT_METHOD; 23 private static final Method GET_GENERATED_KEYS_METHOD; 24 25 static { 26 try { 27 RETURN_GENERATED_KEYS = Statement .class.getDeclaredField("RETURN_GENERATED_KEYS").getInt(PreparedStatement .class); 28 PREPARE_STATEMENT_METHOD = Connection .class.getMethod( "prepareStatement", new Class [] {String .class, Integer.TYPE} ); 29 GET_GENERATED_KEYS_METHOD = Statement .class.getDeclaredMethod("getGeneratedKeys", null); 30 } 31 catch (Exception e) { 32 throw new AssertionFailure("could not initialize getGeneratedKeys() support", e); 33 } 34 } 35 36 public static PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException { 37 Object [] args = new Object [] { sql, new Integer (RETURN_GENERATED_KEYS) } ; 38 try { 39 return (PreparedStatement ) PREPARE_STATEMENT_METHOD.invoke(conn, args); 40 } 41 catch (InvocationTargetException ite) { 42 if ( ite.getTargetException() instanceof SQLException ) { 43 throw (SQLException ) ite.getTargetException(); 44 } 45 else if ( ite.getTargetException() instanceof RuntimeException ) { 46 throw (RuntimeException ) ite.getTargetException(); 47 } 48 else { 49 throw new AssertionFailure("InvocationTargetException", ite); 50 } 51 } 52 catch (IllegalAccessException iae) { 53 throw new AssertionFailure("IllegalAccessException", iae); 54 } 55 } 56 57 public static ResultSet getGeneratedKey(PreparedStatement ps) throws SQLException { 58 try { 59 return (ResultSet ) GET_GENERATED_KEYS_METHOD.invoke(ps, null); 60 } 61 catch (InvocationTargetException ite) { 62 if ( ite.getTargetException() instanceof SQLException ) { 63 throw (SQLException ) ite.getTargetException(); 64 } 65 else if ( ite.getTargetException() instanceof RuntimeException ) { 66 throw (RuntimeException ) ite.getTargetException(); 67 } 68 else { 69 throw new AssertionFailure("InvocationTargetException", ite); 70 } 71 } 72 catch (IllegalAccessException iae) { 73 throw new AssertionFailure("IllegalAccessException", iae); 74 } 75 } 76 77 } 78 | Popular Tags |