1 19 20 package org.apache.cayenne.dba.derby; 21 22 import java.sql.Connection ; 23 import java.sql.PreparedStatement ; 24 import java.sql.ResultSet ; 25 import java.util.Collections ; 26 27 import org.apache.cayenne.CayenneException; 28 import org.apache.cayenne.access.DataNode; 29 import org.apache.cayenne.access.QueryLogger; 30 import org.apache.cayenne.dba.JdbcPkGenerator; 31 import org.apache.cayenne.map.DbEntity; 32 33 40 public class DerbyPkGenerator extends JdbcPkGenerator { 41 42 static final String SELECT_QUERY = "SELECT NEXT_ID FROM AUTO_PK_SUPPORT" 43 + " WHERE TABLE_NAME = ? FOR UPDATE"; 44 45 protected int pkFromDatabase(DataNode node, DbEntity entity) throws Exception { 46 47 if (QueryLogger.isLoggable()) { 48 QueryLogger.logQuery(SELECT_QUERY, Collections 49 .singletonList(entity.getName())); 50 } 51 52 Connection c = node.getDataSource().getConnection(); 53 54 try { 55 PreparedStatement select = c.prepareStatement( 56 SELECT_QUERY, 57 ResultSet.TYPE_FORWARD_ONLY, 58 ResultSet.CONCUR_UPDATABLE); 59 60 select.setString(1, entity.getName()); 61 ResultSet rs = select.executeQuery(); 62 63 if (!rs.next()) { 64 throw new CayenneException("PK lookup failed for table: " 65 + entity.getName()); 66 } 67 68 int nextId = rs.getInt(1); 69 70 rs.updateInt(1, nextId + pkCacheSize); 71 rs.updateRow(); 72 73 if (rs.next()) { 74 throw new CayenneException("More than one PK record for table: " 75 + entity.getName()); 76 } 77 78 rs.close(); 79 80 select.close(); 81 c.commit(); 82 83 return nextId; 84 } 85 finally { 86 c.close(); 87 } 88 } 89 } 90
| Popular Tags
|