1 22 package org.jboss.ejb.plugins.cmp.jdbc.keygen; 23 24 import java.lang.reflect.Field ; 25 import java.lang.reflect.Method ; 26 import java.sql.Connection ; 27 import java.sql.PreparedStatement ; 28 import java.sql.ResultSet ; 29 import java.sql.SQLException ; 30 import javax.ejb.EJBException ; 31 32 import org.jboss.deployment.DeploymentException; 33 import org.jboss.ejb.plugins.cmp.jdbc.JDBCIdentityColumnCreateCommand; 34 import org.jboss.ejb.plugins.cmp.jdbc.JDBCStoreManager; 35 import org.jboss.ejb.plugins.cmp.jdbc.JDBCUtil; 36 import org.jboss.ejb.EntityEnterpriseContext; 37 38 45 public class JDBC30GeneratedKeysCreateCommand extends JDBCIdentityColumnCreateCommand 46 { 47 private static final Method CONNECTION_PREPARE; 48 private static final Integer GENERATE_KEYS; 49 private static final Method GET_GENERATED_KEYS; 50 static { 51 Method prepare, getGeneratedKeys; 52 Integer generateKeys; 53 try { 54 prepare = Connection .class.getMethod("prepareStatement", new Class [] {String .class, int.class}); 55 getGeneratedKeys = PreparedStatement .class.getMethod("getGeneratedKeys", null); 56 Field f = PreparedStatement .class.getField("RETURN_GENERATED_KEYS"); 57 generateKeys = (Integer ) f.get(PreparedStatement .class); 58 } catch (Exception e) { 59 prepare = null; 60 getGeneratedKeys = null; 61 generateKeys = null; 62 } 63 CONNECTION_PREPARE = prepare; 64 GET_GENERATED_KEYS = getGeneratedKeys; 65 GENERATE_KEYS = generateKeys; 66 } 67 68 public void init(JDBCStoreManager manager) throws DeploymentException 69 { 70 if (CONNECTION_PREPARE == null) { 71 throw new DeploymentException("Create command requires JDBC 3.0 (JDK1.4+)"); 72 } 73 super.init(manager); 74 } 75 76 protected PreparedStatement prepareStatement(Connection c, String sql, EntityEnterpriseContext ctx) throws SQLException 77 { 78 try { 79 return (PreparedStatement ) CONNECTION_PREPARE.invoke(c, new Object [] { sql, GENERATE_KEYS }); 80 } catch (Exception e) { 81 throw processException(e); 82 } 83 } 84 85 protected int executeInsert(int paramIndex, PreparedStatement ps, EntityEnterpriseContext ctx) throws SQLException 86 { 87 int rows = ps.executeUpdate(); 88 ResultSet rs = null; 89 try { 90 rs = (ResultSet ) GET_GENERATED_KEYS.invoke(ps, null); 91 if (!rs.next()) { 92 throw new EJBException ("getGeneratedKeys returned an empty ResultSet"); 94 } 95 pkField.loadInstanceResults(rs, 1, ctx); 96 } catch (RuntimeException e) { 97 throw e; 98 } catch (Exception e) { 99 throw new EJBException ("Error extracting generated keys", e); 101 } finally { 102 JDBCUtil.safeClose(rs); 103 } 104 return rows; 105 } 106 } 107 | Popular Tags |