⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 basepeer.java

📁 另外一种持久性o/m软件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
package org.apache.torque.util;/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.Serializable;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.Hashtable;import java.util.Iterator;import java.util.List;import java.util.Set;import org.apache.commons.lang.StringUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.torque.Torque;import org.apache.torque.TorqueException;import org.apache.torque.adapter.DB;import org.apache.torque.map.ColumnMap;import org.apache.torque.map.DatabaseMap;import org.apache.torque.map.MapBuilder;import org.apache.torque.map.TableMap;import org.apache.torque.oid.IdGenerator;import org.apache.torque.om.NumberKey;import org.apache.torque.om.ObjectKey;import org.apache.torque.om.SimpleKey;import org.apache.torque.om.StringKey;import com.workingdogs.village.Column;import com.workingdogs.village.DataSet;import com.workingdogs.village.KeyDef;import com.workingdogs.village.QueryDataSet;import com.workingdogs.village.Record;import com.workingdogs.village.Schema;import com.workingdogs.village.TableDataSet;/** * This is the base class for all Peer classes in the system.  Peer * classes are responsible for isolating all of the database access * for a specific business object.  They execute all of the SQL * against the database.  Over time this class has grown to include * utility methods which ease execution of cross-database queries and * the implementation of concrete Peers. * * @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a> * @author <a href="mailto:jmcnally@collab.net">John D. McNally</a> * @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a> * @author <a href="mailto:stephenh@chase3000.com">Stephen Haberman</a> * @author <a href="mailto:mpoeschl@marmot.at">Martin Poeschl</a> * @author <a href="mailto:vido@ldh.org">Augustin Vidovic</a> * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a> * @version $Id: BasePeer.java,v 1.82 2005/06/27 20:34:41 tfischer Exp $ */public abstract class BasePeer         implements Serializable{    /** Constant criteria key to reference ORDER BY columns. */    public static final String ORDER_BY = "ORDER BY";    /**     * Constant criteria key to remove Case Information from     * search/ordering criteria.     */    public static final String IGNORE_CASE = "IgNOrE cAsE";    /** Classes that implement this class should override this value. */    public static final String TABLE_NAME = "TABLE_NAME";    /** Hashtable that contains the cached mapBuilders. */    private static Hashtable mapBuilders = new Hashtable(5);    /** the log */    protected static Log log = LogFactory.getLog(BasePeer.class);    private static void throwTorqueException(Exception e)        throws TorqueException    {        if (e instanceof TorqueException)         {            throw (TorqueException) e;        }        else         {            throw new TorqueException(e);        }    }    /**     * Sets up a Schema for a table.  This schema is then normally     * used as the argument for initTableColumns().     *     * @param tableName The name of the table.     * @return A Schema.     */    public static Schema initTableSchema(String tableName)    {        return initTableSchema(tableName, Torque.getDefaultDB());    }    /**     * Sets up a Schema for a table.  This schema is then normally     * used as the argument for initTableColumns     *     * @param tableName The propery name for the database in the     * configuration file.     * @param dbName The name of the database.     * @return A Schema.     */    public static Schema initTableSchema(String tableName, String dbName)    {        Schema schema = null;        Connection con = null;        try        {            con = Torque.getConnection(dbName);            schema = new Schema().schema(con, tableName);        }        catch (Exception e)        {            log.error(e);            throw new Error("Error in BasePeer.initTableSchema("                    + tableName                    + "): "                    + e.getMessage());        }        finally        {            Torque.closeConnection(con);        }        return schema;    }    /**     * Creates a Column array for a table based on its Schema.     *     * @param schema A Schema object.     * @return A Column[].     */    public static Column[] initTableColumns(Schema schema)    {        Column[] columns = null;        try        {            int numberOfColumns = schema.numberOfColumns();            columns = new Column[numberOfColumns];            for (int i = 0; i < numberOfColumns; i++)            {                columns[i] = schema.column(i + 1);            }        }        catch (Exception e)        {            log.error(e);            throw new Error(                "Error in BasePeer.initTableColumns(): " + e.getMessage());        }        return columns;    }    /**     * Convenience method to create a String array of column names.     *     * @param columns A Column[].     * @return A String[].     */    public static String[] initColumnNames(Column[] columns)    {        String[] columnNames = null;        columnNames = new String[columns.length];        for (int i = 0; i < columns.length; i++)        {            columnNames[i] = columns[i].name().toUpperCase();        }        return columnNames;    }    /**     * Convenience method to create a String array of criteria keys.     *     * @param tableName Name of table.     * @param columnNames A String[].     * @return A String[].     */    public static String[] initCriteriaKeys(        String tableName,        String[] columnNames)    {        String[] keys = new String[columnNames.length];        for (int i = 0; i < columnNames.length; i++)        {            keys[i] = tableName + "." + columnNames[i].toUpperCase();        }        return keys;    }    /**     * Convenience method that uses straight JDBC to delete multiple     * rows.  Village throws an Exception when multiple rows are     * deleted.     *     * @param con A Connection.     * @param table The table to delete records from.     * @param column The column in the where clause.     * @param value The value of the column.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public static void deleteAll(        Connection con,        String table,        String column,        int value)        throws TorqueException    {        Statement statement = null;        try        {            statement = con.createStatement();            StringBuffer query = new StringBuffer();            query.append("DELETE FROM ")                .append(table)                .append(" WHERE ")                .append(column)                .append(" = ")                .append(value);            statement.executeUpdate(query.toString());        }        catch (SQLException e)        {            throw new TorqueException(e);        }        finally        {            if (statement != null)            {                try                {                    statement.close();                }                catch (SQLException ignored)                {                }            }        }    }    /**     * Convenience method that uses straight JDBC to delete multiple     * rows.  Village throws an Exception when multiple rows are     * deleted.  This method attempts to get the default database from     * the pool.     *     * @param table The table to delete records from.     * @param column The column in the where clause.     * @param value The value of the column.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public static void deleteAll(String table, String column, int value)        throws TorqueException    {        Connection con = null;        try        {            // Get a connection to the db.            con = Torque.getConnection(Torque.getDefaultDB());            deleteAll(con, table, column, value);        }        finally        {            Torque.closeConnection(con);        }    }    /**     * Method to perform deletes based on values and keys in a     * Criteria.     *     * @param criteria The criteria to use.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public static void doDelete(Criteria criteria) throws TorqueException    {        Connection con = null;        try        {            con = Transaction.beginOptional(                    criteria.getDbName(),                    criteria.isUseTransaction());            doDelete(criteria, con);            Transaction.commit(con);        }        catch (TorqueException e)        {            Transaction.safeRollback(con);            throw e;        }    }    /**     * Method to perform deletes based on values and keys in a Criteria.     *     * @param criteria The criteria to use.     * @param con A Connection.     * @throws TorqueException Any exceptions caught during processing will be     *         rethrown wrapped into a TorqueException.     */    public static void doDelete(Criteria criteria, Connection con)        throws TorqueException    {        String dbName = criteria.getDbName();        final DB db = Torque.getDB(dbName);        final DatabaseMap dbMap = Torque.getDatabaseMap(dbName);        // This Callback adds all tables to the Table set which         // are referenced from a cascading criteria. As a result, all        // data that is referenced through foreign keys will also be        // deleted.        SQLBuilder.TableCallback tc = new SQLBuilder.TableCallback() {                public void process (Set tables, String key, Criteria crit)                {                    if (crit.isCascade())                    {                        // This steps thru all the columns in the database.                        TableMap[] tableMaps = dbMap.getTables();                        for (int i = 0; i < tableMaps.length; i++)                        {                            ColumnMap[] columnMaps = tableMaps[i].getColumns();                            for (int j = 0; j < columnMaps.length; j++)                            {                                // Only delete rows where the foreign key is                                // also a primary key.  Other rows need                                // updating, but that is not implemented.                                if (columnMaps[j].isForeignKey()                                        && columnMaps[j].isPrimaryKey()                                        && key.equals(columnMaps[j].getRelatedName()))                                {                                    tables.add(tableMaps[i].getName());                                    crit.add(columnMaps[j].getFullyQualifiedName(),                                            crit.getValue(key));                                }                            }                        }                    }                }            };        Set tables = SQLBuilder.getTableSet(criteria, tc);        try        {            processTables(criteria, tables, con, new ProcessCallback() {                    public void process(String table, String dbName, Record rec)                        throws Exception                    {                        rec.markToBeDeleted();                        rec.save();                    }                });        }        catch (Exception e)        {            throwTorqueException(e);        }    }    /**     * Method to perform inserts based on values and keys in a     * Criteria.     * <p>     * If the primary key is auto incremented the data in Criteria     * will be inserted and the auto increment value will be returned.     * <p>     * If the primary key is included in Criteria then that value will     * be used to insert the row.     * <p>     * If no primary key is included in Criteria then we will try to     * figure out the primary key from the database map and insert the     * row with the next available id using util.db.IDBroker.     * <p>     * If no primary key is defined for the table the values will be     * inserted as specified in Criteria and -1 will be returned.     *     * @param criteria Object containing values to insert.     * @return An Object which is the id of the row that was inserted     * (if the table has a primary key) or null (if the table does not

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -