1 22 package org.jboss.ejb.plugins.cmp.jdbc; 23 24 import java.sql.Connection ; 25 import java.sql.PreparedStatement ; 26 import java.sql.SQLException ; 27 import java.sql.ResultSet ; 28 import javax.ejb.CreateException ; 29 import javax.ejb.DuplicateKeyException ; 30 31 import org.jboss.ejb.EntityEnterpriseContext; 32 import org.jboss.deployment.DeploymentException; 33 34 41 public abstract class JDBCInsertPKCreateCommand extends JDBCAbstractCreateCommand 42 { 43 protected String existsSQL; 44 45 public void init(JDBCStoreManager manager) throws DeploymentException 46 { 47 super.init(manager); 48 49 if(exceptionProcessor == null) 52 { 53 initExistsSQL(); 54 } 55 } 56 57 protected void initExistsSQL() 58 { 59 StringBuffer sql = new StringBuffer (300); 60 sql.append(SQLUtil.SELECT).append("COUNT(*)").append(SQLUtil.FROM) 61 .append(entity.getQualifiedTableName()) 62 .append(SQLUtil.WHERE); 63 SQLUtil.getWhereClause(entity.getPrimaryKeyFields(), sql); 64 existsSQL = sql.toString(); 65 if(debug) 66 { 67 log.debug("Entity Exists SQL: " + existsSQL); 68 } 69 } 70 71 protected void beforeInsert(EntityEnterpriseContext ctx) throws CreateException 72 { 73 if(existsSQL != null) 75 { 76 Connection c = null; 77 PreparedStatement ps = null; 78 ResultSet rs = null; 79 try 80 { 81 if(debug) 82 log.debug("Executing SQL: " + existsSQL); 83 84 c = entity.getDataSource().getConnection(); 85 ps = c.prepareStatement(existsSQL); 86 87 Object pk = entity.extractPrimaryKeyFromInstance(ctx); 90 entity.setPrimaryKeyParameters(ps, 1, pk); 91 92 rs = ps.executeQuery(); 93 if(!rs.next()) 94 { 95 throw new CreateException ("Error checking if entity with primary pk " + pk + "exists: SQL returned no rows"); 96 } 97 if(rs.getInt(1) > 0) 98 { 99 throw new DuplicateKeyException ("Entity with primary key " + pk + " already exists"); 100 } 101 } 102 catch(SQLException e) 103 { 104 log.error("Error checking if entity exists", e); 105 throw new CreateException ("Error checking if entity exists:" + e); 106 } 107 finally 108 { 109 JDBCUtil.safeClose(rs); 110 JDBCUtil.safeClose(ps); 111 JDBCUtil.safeClose(c); 112 } 113 } 114 } 115 } 116 | Popular Tags |