📄 basepeer.java
字号:
/** * Utility method which executes a given sql statement. This * method should be used for update, insert, and delete * statements. Use executeQuery() for selects. * * @param statementString A String with the sql statement to execute. * @return The number of rows affected. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static int executeStatement(String statementString) throws TorqueException { return executeStatement(statementString, Torque.getDefaultDB()); } /** * Utility method which executes a given sql statement. This * method should be used for update, insert, and delete * statements. Use executeQuery() for selects. * * @param statementString A String with the sql statement to execute. * @param dbName Name of database to connect to. * @return The number of rows affected. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static int executeStatement(String statementString, String dbName) throws TorqueException { Connection con = null; int rowCount = -1; try { con = Torque.getConnection(dbName); rowCount = executeStatement(statementString, con); } finally { Torque.closeConnection(con); } return rowCount; } /** * Utility method which executes a given sql statement. This * method should be used for update, insert, and delete * statements. Use executeQuery() for selects. * * @param statementString A String with the sql statement to execute. * @param con A Connection. * @return The number of rows affected. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static int executeStatement(String statementString, Connection con) throws TorqueException { int rowCount = -1; Statement statement = null; try { statement = con.createStatement(); rowCount = statement.executeUpdate(statementString); } catch (SQLException e) { throw new TorqueException(e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { throw new TorqueException(e); } } } return rowCount; } /** * If the user specified that (s)he only wants to retrieve a * single record and multiple records are retrieved, this method * is called to handle the situation. The default behavior is to * throw an exception, but subclasses can override this method as * needed. * * @param ds The DataSet which contains multiple records. * @exception TorqueException Couldn't handle multiple records. */ protected static void handleMultipleRecords(DataSet ds) throws TorqueException { throw new TorqueException("Criteria expected single Record and " + "Multiple Records were selected"); } /** * This method returns the MapBuilder specified in the name * parameter. You should pass in the full path to the class, ie: * org.apache.torque.util.db.map.TurbineMapBuilder. The * MapBuilder instances are cached in this class for speed. * * @param name name of the MapBuilder * @return A MapBuilder, not null * @throws TorqueException if the Map Builder cannot be instantiated */ public static MapBuilder getMapBuilder(String name) throws TorqueException { synchronized (mapBuilders) { try { MapBuilder mb = (MapBuilder) mapBuilders.get(name); if (mb == null) { mb = (MapBuilder) Class.forName(name).newInstance(); // Cache the MapBuilder before it is built. mapBuilders.put(name, mb); } // Build the MapBuilder in its own synchronized block to // avoid locking up the whole Hashtable while doing so. // Note that *all* threads need to do a sync check on isBuilt() // to avoid grabing an uninitialized MapBuilder. This, however, // is a relatively fast operation. if (mb.isBuilt()) { return mb; } try { mb.doBuild(); } catch (Exception e) { // need to think about whether we'd want to remove // the MapBuilder from the cache if it can't be // built correctly...? pgo throw e; } return mb; } catch (Exception e) { log.error("BasePeer.MapBuilder failed trying to instantiate: " + name, e); throw new TorqueException(e); } } } /** * Performs a SQL <code>select</code> using a PreparedStatement. * Note: this method does not handle null criteria values. * * @param criteria * @param con * @return a List of Record objects. * @throws TorqueException Error performing database query. */ public static List doPSSelect(Criteria criteria, Connection con) throws TorqueException { List v = null; StringBuffer qry = new StringBuffer(); List params = new ArrayList(criteria.size()); createPreparedStatement(criteria, qry, params); PreparedStatement statement = null; try { statement = con.prepareStatement(qry.toString()); for (int i = 0; i < params.size(); i++) { Object param = params.get(i); if (param instanceof java.sql.Date) { statement.setDate(i + 1, (java.sql.Date) param); } else if (param instanceof NumberKey) { statement.setBigDecimal(i + 1, ((NumberKey) param).getBigDecimal()); } else { statement.setString(i + 1, param.toString()); } } QueryDataSet qds = null; try { qds = new QueryDataSet(statement.executeQuery()); v = getSelectResults(qds); } finally { VillageUtils.close(qds); } } catch (Exception e) { throwTorqueException(e); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { throw new TorqueException(e); } } } return v; } /** * Do a Prepared Statement select according to the given criteria * * @param criteria * @return a List of Record objects. * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static List doPSSelect(Criteria criteria) throws TorqueException { Connection con = Torque.getConnection(criteria.getDbName()); List v = null; try { v = doPSSelect(criteria, con); } finally { Torque.closeConnection(con); } return v; } /** * Create a new PreparedStatement. It builds a string representation * of a query and a list of PreparedStatement parameters. * * @param criteria * @param queryString * @param params * @throws TorqueException Any exceptions caught during processing will be * rethrown wrapped into a TorqueException. */ public static void createPreparedStatement( Criteria criteria, StringBuffer queryString, List params) throws TorqueException { Query query = SQLBuilder.buildQueryClause(criteria, params, new SQLBuilder.QueryCallback() { public String process(Criteria.Criterion criterion, List params) { StringBuffer sb = new StringBuffer(); criterion.appendPsTo(sb, params); return sb.toString(); } }); String sql = query.toString(); log.debug(sql); queryString.append(sql); } /** * Process the result of a Table list generation. * This runs the statements onto the list of tables and * provides a callback hook to add functionality. * * This method should've been in SQLBuilder, but is uses the handleMultipleRecords callback thingie.. * * @param crit The criteria * @param tables A set of Tables to run on * @param con The SQL Connection to run the statements on * @param pc A ProcessCallback object * * @throws Exception An Error occured (should be wrapped into TorqueException) */ private static void processTables(Criteria crit, Set tables, Connection con, ProcessCallback pc) throws Exception { String dbName = crit.getDbName(); DB db = Torque.getDB(dbName); DatabaseMap dbMap = Torque.getDatabaseMap(dbName); // create the statements for the tables for (Iterator it = tables.iterator(); it.hasNext(); ) { String table = (String) it.next(); KeyDef kd = new KeyDef(); Set whereClause = new HashSet(); ColumnMap[] columnMaps = dbMap.getTable(table).getColumns(); for (int j = 0; j < columnMaps.length; j++) { ColumnMap colMap = columnMaps[j]; if (colMap.isPrimaryKey()) { kd.addAttrib(colMap.getColumnName()); } String key = new StringBuffer(colMap.getTableName()) .append('.') .append(colMap.getColumnName()) .toString(); if (crit.containsKey(key)) { if (crit .getComparison(key) .equals(Criteria.CUSTOM)) { whereClause.add(crit.getString(key)); } else { whereClause.add( SqlExpression.build( colMap.getColumnName(), crit.getValue(key), crit.getComparison(key), crit.isIgnoreCase(), db)); } } } // Execute the statement for each table TableDataSet tds = null; try { String tableName = SQLBuilder.getFullTableName(table, dbName); // Get affected records. tds = new TableDataSet(con, tableName, kd); String sqlSnippet = StringUtils.join(whereClause.iterator(), " AND "); if (log.isDebugEnabled()) { log.debug("BasePeer: whereClause=" + sqlSnippet); } tds.where(sqlSnippet); tds.fetchRecords(); if (tds.size() > 1 && crit.isSingleRecord()) { handleMultipleRecords(tds); } for (int j = 0; j < tds.size(); j++) { Record rec = tds.getRecord(j); if (pc != null) { // Table name _without_ schema! pc.process(table, dbName, rec); } } } finally { VillageUtils.close(tds); } } } /** * Inner Interface that defines the Callback method for * the Record Processing */ protected interface ProcessCallback { void process (String table, String dbName, Record rec) throws Exception; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -