1 22 package org.jboss.ejb.plugins.cmp.jdbc.keygen; 23 24 import java.sql.Connection ; 25 import java.sql.ResultSet ; 26 import java.sql.SQLException ; 27 import java.sql.Statement ; 28 import javax.ejb.CreateException ; 29 import javax.sql.DataSource ; 30 31 import org.jboss.deployment.DeploymentException; 32 import org.jboss.ejb.EntityEnterpriseContext; 33 import org.jboss.ejb.plugins.cmp.jdbc.bridge.JDBCCMPFieldBridge; 34 import org.jboss.ejb.plugins.cmp.jdbc.metadata.JDBCEntityCommandMetaData; 35 import org.jboss.ejb.plugins.cmp.jdbc.JDBCInsertPKCreateCommand; 36 import org.jboss.ejb.plugins.cmp.jdbc.JDBCStoreManager; 37 import org.jboss.ejb.plugins.cmp.jdbc.JDBCUtil; 38 39 47 public class JDBCPkSqlCreateCommand extends JDBCInsertPKCreateCommand 48 { 49 protected String pkSQL; 50 protected JDBCCMPFieldBridge pkField; 51 52 public void init(JDBCStoreManager manager) throws DeploymentException 53 { 54 super.init(manager); 55 pkField = getGeneratedPKField(); 56 } 57 58 protected void initEntityCommand(JDBCEntityCommandMetaData entityCommand) throws DeploymentException 59 { 60 super.initEntityCommand(entityCommand); 61 62 pkSQL = entityCommand.getAttribute("pk-sql"); 63 if(pkSQL == null) 64 { 65 throw new DeploymentException("pk-sql attribute must be set for entity " + entity.getEntityName()); 66 } 67 if(debug) 68 { 69 log.debug("Generate PK sql is: " + pkSQL); 70 } 71 } 72 73 protected void generateFields(EntityEnterpriseContext ctx) throws CreateException 74 { 75 super.generateFields(ctx); 76 77 Connection con = null; 78 Statement s = null; 79 ResultSet rs = null; 80 try 81 { 82 if(debug) 83 { 84 log.debug("Executing SQL: " + pkSQL); 85 } 86 87 DataSource dataSource = entity.getDataSource(); 88 con = dataSource.getConnection(); 89 s = con.createStatement(); 90 91 rs = s.executeQuery(pkSQL); 92 if(!rs.next()) 93 { 94 throw new CreateException ("Error fetching next primary key value: result set contains no rows"); 95 } 96 pkField.loadInstanceResults(rs, 1, ctx); 97 } 98 catch(SQLException e) 99 { 100 log.error("Error fetching the next primary key value", e); 101 throw new CreateException ("Error fetching the next primary key value:" + e); 102 } 103 finally 104 { 105 JDBCUtil.safeClose(rs); 106 JDBCUtil.safeClose(s); 107 JDBCUtil.safeClose(con); 108 } 109 } 110 } 111 | Popular Tags |